Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit c315f38

Browse files
authoredOct 3, 2018
Created cutRod.py
Python Implementation of Rod Cutting.
1 parent 82a0f3a commit c315f38

File tree

1 file changed

+23
-0
lines changed
  • Competitive Coding/Dynamic Programming/cutRod

1 file changed

+23
-0
lines changed
 
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# A Dynamic Programming solution for Rod cutting problem
2+
INT_MIN = -32767
3+
4+
# Returns the best obtainable price for a rod of length n and
5+
# price[] as prices of different pieces
6+
def cutRod(price, n):
7+
val = [0 for x in range(n+1)]
8+
val[0] = 0
9+
10+
# Build the table val[] in bottom up manner and return
11+
# the last entry from the table
12+
for i in range(1, n+1):
13+
max_val = INT_MIN
14+
for j in range(i):
15+
max_val = max(max_val, price[j] + val[i-j-1])
16+
val[i] = max_val
17+
18+
return val[n]
19+
20+
# Driver program to test above functions
21+
arr = [1, 5, 8, 9, 10, 17, 17, 20]
22+
size = len(arr)
23+
print("Maximum Obtainable Value is " + str(cutRod(arr, size)))

0 commit comments

Comments
 (0)
Please sign in to comment.