Grokking Dynamic Programming Patterns for Coding Interviews

0% completed

Rod Cutting

Problem Statement

Given a rod of length 'n', we are asked to cut the rod and sell the pieces in a way that will maximize the profit. We are also given the price of every piece of length 'i' where '1 <= i <= n'.

Example:

Lengths: [1, 2, 3, 4, 5]
Prices: [2, 6, 7, 10, 13]
Rod Length: 5

Let's try different combinations of cutting the rod:

Five pieces of length 1 => 10 price
Two pieces of length 2 and one piece of length 1 => 14 price
One piece of length 3 and two pieces of length 1 => 11 price
One piece of length 3 and one piece of length 2 => 13 price

.....

.....

.....

Like the course? Get enrolled and start learning!
S

Shan

· 4 years ago

It makes sense to skip the brute force and top down. But it is still useful to provide both of the implementations (no deep dive required). This prevents users from having to search online to find them.

Users can then try each approach and build up to bottom up.

Mohammed Dh Abbas

Mohammed Dh Abbas

· 2 years ago

class Solution: def solveRodCutting(self, lengths, prices, n): def dp(index, acc, length, memo): if (index, acc, length) in memo: return memo[(index, acc, length)] if index == len(lengths): return acc result = 0 if length + lengths[index] <= n: with_item = dp(index, acc + prices[index], length + lengths[index], memo) without_item = dp(index + 1, acc, length, memo) result = max(with_item, without_item) else: result = dp(index + 1, acc, length, memo) # without item // skipping memo[(index, acc, length)] = result return result return dp(0, 0, 0, {})
Online Courses

Online Courses

· 4 months ago

My solution, from brute force to memoisation, 2DP, and 1D DP:

class Solution: def solveRodCutting_bruteforce(self, lengths, prices, n): num_lens = len(lengths) if num_lens == 0: return 0 def rod_cutting(idx, cur_len): if idx == num_lens or cur_len == n: return 0 # no cut no_cut = rod_cutting(idx + 1, cur_len) # cut cut = 0 if cur_len + lengths[idx] <= n: cut = prices[idx] + rod_cutting(idx, cur_len + lengths[idx]) result = max(no_cut, cut) return result return rod_cutting(0, 0) def solveRodCutting_memoize(self, lengths, prices, n): num_lens = len(lengths) if num_lens == 0: return 0 memo = {} def rod_cutting(idx, cur_len): if idx ==