diff --git a/Dynamic-Programming/RodCutting.js b/Dynamic-Programming/RodCutting.js new file mode 100644 index 000000000..1e8bac82e --- /dev/null +++ b/Dynamic-Programming/RodCutting.js @@ -0,0 +1,17 @@ +/* + * 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) { + 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] +} diff --git a/Dynamic-Programming/tests/RodCutting.test.js b/Dynamic-Programming/tests/RodCutting.test.js new file mode 100644 index 000000000..349ea2997 --- /dev/null +++ b/Dynamic-Programming/tests/RodCutting.test.js @@ -0,0 +1,21 @@ +import { rodCut } from '../RodCutting' + +test('Test Case 1', () => { + expect(rodCut([1, 5, 8, 9, 10, 17, 17, 20], 8)).toBe(22) +}) + +test('Test Case 2', () => { + expect(rodCut([1, 5, 4, 2, 1, 11, 19, 12], 8)).toBe(20) +}) + +test('Test Case 3', () => { + expect(rodCut([1, 2, 1], 3)).toBe(3) +}) + +test('Test Case 4', () => { + expect(rodCut([5, 4, 3, 2, 1], 5)).toBe(25) +}) + +test('Test Case 5', () => { + expect(rodCut([3, 5, 8, 8, 10, 16, 14, 19], 8)).toBe(24) +})