forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Rod Cutting Dp Problem
- Loading branch information
Showing
1 changed file
with
25 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
# A Dynamic Programming solution for Rod cutting problem | ||
INT_MIN = -32767 | ||
|
||
# Returns the best obtainable price for a rod of length n and | ||
# price[] as prices of different pieces | ||
def cutRod(price, n): | ||
val = [0 for x in range(n+1)] | ||
val[0] = 0 | ||
|
||
# Build the table val[] in bottom up manner and return | ||
# the last entry from the table | ||
for i in range(1, n+1): | ||
max_val = INT_MIN | ||
for j in range(i): | ||
max_val = max(max_val, price[j] + val[i-j-1]) | ||
val[i] = max_val | ||
|
||
return val[n] | ||
|
||
# Driver program to test above functions | ||
arr = [1, 5, 8, 9, 10, 17, 17, 20] | ||
size = len(arr) | ||
print("Maximum Obtainable Value is " + str(cutRod(arr, size))) | ||
|
||
# This code is contributed by Bhavya Jain |