Skip to content

Commit 50b02f8

Browse files
authored
Create game_optimal_strategy_DP.py
1 parent b82cd35 commit 50b02f8

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Copyright (c) June 02, 2017 CareerMonk Publications and others.
2+
3+
# Creation Date : 2017-06-02 06:15:46
4+
# Last modification : 2017-06-02
5+
# Modified by : Narasimha Karumanchi
6+
# Book Title : Algorithm Design Techniques
7+
# Warranty : This software is provided "as is" without any
8+
# warranty; without even the implied warranty of
9+
# merchantability or fitness for a particular purpose.
10+
11+
def game(coins):
12+
n = len(coins)
13+
V = [[0 for i in range(n)] for j in range(n)]
14+
#Initialize for length=1
15+
for i in range(n):
16+
V[i][i] = coins[i]
17+
18+
#Generate coins for length=2, 3 ....
19+
#size+1 to include all coins!
20+
for l in range(2, n+1):
21+
#start value range 0 & 1
22+
for i in range(0, n):
23+
#end coins changes based on i and length(l)
24+
#size =2 -> [0, 1] [1, 2],[2, 3]
25+
#size =3 -> [0, 2], [1, 3]
26+
j = i + l - 1
27+
28+
#IMPORTANT: break when i or j index is not valid
29+
if i >= n or i+1 >= n or i+2 >= n or j >= n:
30+
break
31+
32+
#option 1: pick i
33+
path1 = coins[i] + min(V[i+2][j],V[i+1][j-1])
34+
35+
#option 2: pick j
36+
path2 = coins[j] + min(V[i+1][j-1],V[i][j-2])
37+
V[i][j] = max(path1, path2)
38+
#print(V)
39+
return V[0][n-1]
40+
41+
# row of n coins
42+
coins = [4, 3, 3, 4, 2, 3]
43+
print game(coins)

0 commit comments

Comments
 (0)