8000 Adding Rod Cutting problem · jeffmikels/python@8fb113d · GitHub
[go: up one dir, main page]

Skip to content

Commit 8fb113d

Browse files
beingadityakabranhe
authored andcommitted
Adding Rod Cutting problem
1 parent d2e1c41 commit 8fb113d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

dynamic_programming/rod_cutting.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
This module calculates optimized solution for rod cutting
3+
by function rod_cutting() with arguments as defined
4+
in main()
5+
"""
6+
7+
8+
def rod_cutting(price):
9+
"""
10+
Computes maximum money that can be earned by cutting
11+
a rod of length len(price) (Bottom-Up Approach).
12+
Time Complexity : O((len(price))^2)
13+
Space Complexity : O(len(price))
14+
:param price: List in which price[i] denotes price of rod of length i.
15+
:return: returns optimal solution for rod of length len(price).
16+
"""
17+
length = len(price)
18+
opt_price = [0] * (length + 1)
19+
20+
for i in range(1, length + 1):
21+
opt_price[i] = max(
22+
[-1] + [price[j] + opt_price[i - j - 1] for j in range(i)])
23+
return opt_price[length]
24+
25+
26+
def main():
27+
"""
28+
Main Function of this program.
29+
"""
30+
price = [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]
31+
print(rod_cutting(price))
32+
33+
34+
if __name__ == '__main__':
35+
main()

0 commit comments

Comments
 (0)
0