Saturday, March 19, 2016

Pickup coin/gold | allenlipeng47

Pickup coin/gold | allenlipeng47
Number of coins lined up, two persons take turn to pick up coins from both ends, what is the maximum total sum of money first person can pick?

his one is a good one for dp. I wrote it in recursive way before. The formula for this problem is below:DP(i,j) = Max(* Min(DP(i,j-2), DP(i+1,j-1))+coins[j],* Min(DP(i+2,j), DP(i+1,j-1))+coins[i])

This time, I tried with a less time complexity O(n^2). Key idea for this is to use a 2-d array to memorize sub-solution. For example, 2-d array memo[i][j] saves the max value between gold[i], gold[i+1], … gold[j]. Take [1, 2, 3, 1] for example, the memo[][] array and the calculation sequence will be like below:

https://github.com/allenlipeng47/algorithm/blob/master/src/main/java/com/pli/project/algorithm/exercise2014/GetMaxGold.java
/*
* Suppose the pots are arranged in L[0] to L[n].
* First player can pick either L[0] or L[n]. If
* he picks L[0] Second player can pick either
* L[1] or L[n]. If first picks L[n], second
* player can pick L[0] or L[n-1]. As the second
* player is also playing optimally he will also
* use the same strategy as the first player. Let
* us assume f(i,j) is the number of coins a
* player would get if he plays optimally from a
* point when two ends are i and j (0<=i<=j<=n).
* So f(0,n) would be the number of coins that
* first player would get after playing optimally.
* As second player is also playing optimally, he
* will pick a pot such that after his picking first
* player will get fewer gold if played optimally.
* If second player takes pot number 1, player 1
* will get f(2,n). If second player takes pot
* number n, first player will get f(1,n-1). Second
* player will play such that 1st player gets minimum
* of these two options. So if first player takes pot
* 0 his final count of gold will be L[0]+Min(f(2,n),f(1,n-1)).
* Similarly if he picks the last pot this total count
* will be L[n]+Min(f(0,n-2),f(1,n-1)). From these two
* items whichever is greater First player should pick
* that, and that should be his winning strategy as playing first.
*/public static void main(String[] args) {int[] gold = {1,2,3,1};int[][] memo = new int[gold.length][gold.length];printArray(gold, 0, gold.length-1);System.out.println(getMaxGold(gold, 0, gold.length-1, memo));System.out.println(getMaxGold(gold));}