Friday, May 29, 2015

[LintCode] Coins in a Line III

There are n coins in a line. Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.
Could you please decide the first player will win or lose?

Example

Given array A = [3,2,2], return true.
Given array A = [1,2,4], return true.
Given array A = [1,20,4], return false.

Challenge
Follow Up Question:
If n is even. Is there any hacky algorithm that can decide whether first player will win or lose in O(1) memory and O(n) time?

This is similar to Coins in a Line II. The only difference is that it's in a 2-d scope.
Recursive: Complexity is power(2,n).
    int firstWillWin(vector<int> &values, int s, int e) {
        if(s == e) return values[s];
        return max( values[s] - firstWillWin(values, s+1, e),
                   values[e] - firstWillWin(values, s, e-1) );
        
    }
    bool firstWillWin(vector<int> &values) {
        int len = values.size();
        if(len<=2) return true;
        return firstWillWin(values, 0, len-1) > 0;
    }
DP:
    bool firstWillWin(vector<int> &values) {
        int len = values.size();
        if(len<=2) return true;
        vector<vector<int>> f(len, vector<int>(len,0));        
        for(int i=0;i<len;i++) f[i][i] = values[i];
        for(int i=len-2;i>=0;i--)
        {
            for(int j=i+1;j<len;j++)
            {
                f[i][j] = max(values[i] - f[i+1][j], values[j] - f[i][j-1]);
            }
        }
        return f[0][len-1] > 0;
    }