Skip to content

Commit e4d69f8

Browse files
authored
chore: Merge pull request #776 from raghhavtaneja/raghhavtaneja-patch-1
Create RodCutting.js
2 parents 3cac210 + 5210273 commit e4d69f8

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Dynamic-Programming/RodCutting.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/*
2+
* You are given a rod of 'n' length and an array of prices associated with all the lengths less than 'n'.
3+
* Find the maximum profit possible by cutting the rod and selling the pieces.
4+
*/
5+
6+
export function rodCut (prices, n) {
7+
const memo = new Array(n + 1)
8+
memo[0] = 0
9+
10+
for (let i = 1; i <= n; i++) {
11+
let maxVal = Number.MIN_VALUE
12+
for (let j = 0; j < i; j++) { maxVal = Math.max(maxVal, prices[j] + memo[i - j - 1]) }
13+
memo[i] = maxVal
14+
}
15+
16+
return memo[n]
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { rodCut } from '../RodCutting'
2+
3+
test('Test Case 1', () => {
4+
expect(rodCut([1, 5, 8, 9, 10, 17, 17, 20], 8)).toBe(22)
5+
})
6+
7+
test('Test Case 2', () => {
8+
expect(rodCut([1, 5, 4, 2, 1, 11, 19, 12], 8)).toBe(20)
9+
})
10+
11+
test('Test Case 3', () => {
12+
expect(rodCut([1, 2, 1], 3)).toBe(3)
13+
})
14+
15+
test('Test Case 4', () => {
16+
expect(rodCut([5, 4, 3, 2, 1], 5)).toBe(25)
17+
})
18+
19+
test('Test Case 5', () => {
20+
expect(rodCut([3, 5, 8, 8, 10, 16, 14, 19], 8)).toBe(24)
21+
})

0 commit comments

Comments
 (0)