Coins in a line II

There are n coins with different value in a line. Two players take turns to take one or two coins from left side until there are no more coins left. The player who take the coins with the most value wins.

Could you please decide the first player will win or lose? Example Given values array A = [1,2,2], return true.

Given A = [1,2,4], return false.

Key Points: O(2n) O(n)

  1. Method 1: f(i)=max(A[i]+sum[i+1]f(i+1),A[i]+A[i+1]+sum[i+2]f(i+2))f(i) = max(A[i]+sum[i+1]-f(i+1),A[i]+A[i+1]+sum[i+2]-f(i+2))
  2. Method 2: f(i)=max(A[i]+min(f(i+2),f(i+3)),A[i]+A[i+1]+min(f(i+3),f(i+4)))f(i) = max(A[i]+min(f(i+2),f(i+3)), A[i]+A[i+1]+min(f(i+3),f(i+4)))
  3. This suggest that sum[i]f(i)=min(f(i+1),f(i+2))sum[i]-f(i) = min(f(i+1),f(i+2))
  4. The interesting place is that this problem cant be transformed to n->n-1 format because [1,2,4] will yield different result compare to [4,2,1]. But we can still do the computation in iteration with n->n+1 formula.
  5. Compare to Method 1, Method 2 takes no extra space or time to store sums, but a little bit more complex on computation order.
public boolean firstWillWin(int[] values) {
        int len = values.length;
        if(len==0){return false;}
        if(len<=2){return true;}
        int[] sum= new int[len];
        int total = 0;
        for(int i=len-1; i>=0; i--){
            total+=values[i];
            sum[i]=total;
        }

        int last = values[len-2]+values[len-1], oneBeforeLast = values[len-1];

        for(int i =len-3; i>=0; i--){
            int t = last;
            last = Math.max(values[i]+sum[i+1]-last,values[i]+values[i+1]+sum[i+2]-oneBeforeLast);
            oneBeforeLast = t;

        }
        return last>sum[0]/2;

    }

results matching ""

    No results matching ""