LeetCode in Kotlin

1690. Stone Game VII

Medium

Alice and Bob take turns playing a game, with Alice starting first.

There are n stones arranged in a row. On each player’s turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones’ values in the row. The winner is the one with the higher score when there are no stones left to remove.

Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score’s difference. Alice’s goal is to maximize the difference in the score.

Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob’s score if they both play optimally.

Example 1:

Input: stones = [5,3,1,4,2]

Output: 6

Explanation:

The score difference is 18 - 12 = 6.

Example 2:

Input: stones = [7,90,5,1,100,10,10,2]

Output: 122

Constraints:

Solution

class Solution {
    fun stoneGameVII(stones: IntArray): Int {
        val n = stones.size
        val dp = IntArray(n)
        for (i in n - 1 downTo 0) {
            var j = i + 1
            var sum = stones[i]
            while (j < n) {
                sum += stones[j]
                dp[j] = Math.max(sum - stones[i] - dp[j], sum - stones[j] - dp[j - 1])
                j++
            }
        }
        return dp[n - 1]
    }
}