-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathRodCutting.js
More file actions
31 lines (25 loc) · 726 Bytes
/
RodCutting.js
File metadata and controls
31 lines (25 loc) · 726 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
* You are given a rod of 'n' length and an array of prices associated with all the lengths less than 'n'.
* Find the maximum profit possible by cutting the rod and selling the pieces.
*/
export function rodCut(prices, n) {
if (!Array.isArray(prices)) {
throw new TypeError('Prices must be an array')
}
if (!Number.isInteger(n) || n < 0) {
throw new TypeError('Rod length must be a non-negative integer')
}
if (n === 0) {
return 0
}
const memo = new Array(n + 1)
memo[0] = 0
for (let i = 1; i <= n; i++) {
let maxVal = Number.MIN_VALUE
for (let j = 0; j < i; j++) {
maxVal = Math.max(maxVal, prices[j] + memo[i - j - 1])
}
memo[i] = maxVal
}
return memo[n]
}