# Coins in a Line III

## Question

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?

**Tags**

Dynamic Programming Array Game Theory

**Related Problems**

Medium Coins in a Line II 31 %\
Medium Coins in a Line

## Analysis

类似于系列问题II，可以根据取硬币的流程，画出一个tree:

```
初始：[3, 2, 2]

                  [3, 2, 2]
                   dp[0][2]
                /           \
        取左3  /              \ 取右2
             /                 \
         [2, 2]                [3, 2]
        dp[1][2]              dp[0][1]
          /    \                  /  \
    取左2 /      \ 取右2     取左3 /    \ 取右2
        /         \             /      \
    [2]            [2]        [2]      [3]
  dp[2][2]     dp[1][1]     dp[1][1]   dp[0][0]
```

DP四要素：

* State:
  * `dp[i][j]` 现在还第i到第j的硬币，现在当前取硬币的人（先手）最后最多取硬币价值；这里是区间型DP，下标表示区间范围
* Function:
  * `sum[i][j]`第i到第j的硬币价值总和
  * `dp[i][j] = sum[i][j] - min(dp[i+1][j], dp[i][j-1]);`
* Initialize:
  * `dp[i][i] = coin[i]`
* Answer:
  * `dp[0][n-1]`

运用Memorized Search，记忆化搜索可以优化时间。

## Solution

```java
public class Solution {
    /**
     * @param values: an array of integers
     * @return: a boolean which equals to true if the first player will win
     */
    public boolean firstWillWin(int[] values) {
        if (values == null || values.length == 0) {
            return false;
        }

        int n = values.length;

        int[][] sum = new int[n+1][n+1];
        int[][] dp = new int[n+1][n+1];
        boolean[][] flag = new boolean[n+1][n+1];

        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                if (i == j) {
                    sum[i][j] = values[j];
                } else {
                    sum[i][j] = sum[i][j - 1] + values[j];
                }
            }
        }
        int total = 0;
        for (int i = 0; i < n; i++) {
            total += values[i];
        }

        return (total / 2) < search(0, n - 1, dp, flag, values, sum);
    }

    public int search(int i, int j, int[][] dp, boolean[][] flag, int[] values, int[][] sum) {
        if (flag[i][j]) {
            return dp[i][j];
        }

        flag[i][j] = true;

        if (i == j) {
            dp[i][j] = values[i];
        } else if (i > j) {
            dp[i][j] = 0;
        } else if (i + 1 == j) {
            dp[i][j] = Math.max(values[i], values[j]);
        } else {
            dp[i][j] = sum[i][j] - Math.min(search(i, j - 1, dp, flag, values, sum), search(i + 1, j, dp, flag, values, sum));
        }

        return dp[i][j];
    }

}
```

## Reference

* [Jiuzhang: Coins in a Line III](http://www.jiuzhang.com/solutions/coins-in-a-line-iii/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/dynamic_programming/coins_in_a_line_iii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
