#1563

Stone Game V

Hard
ArrayMathDynamic ProgrammingGame TheoryDynamic ProgrammingPrefix Sums
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal solution uses dynamic programming to store the maximum score that can be achieved for each subarray. By avoiding redundant calculations, we significantly reduce the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP array where dp[i] represents the maximum score obtainable from the first i stones.
  2. 2Step 2: Iterate through all possible split points and calculate the left and right sums using prefix sums for efficiency.
  3. 3Step 3: Update the DP array based on the scores from the splits, considering which row Bob would discard.
solution.py17 lines
1def stoneGameV(stoneValue):
2    n = len(stoneValue)
3    prefix_sum = [0] * (n + 1)
4    for i in range(n):
5        prefix_sum[i + 1] = prefix_sum[i] + stoneValue[i]
6    dp = [0] * n
7    for i in range(1, n):
8        for j in range(i):
9            left_sum = prefix_sum[j + 1]
10            right_sum = prefix_sum[i + 1] - left_sum
11            if left_sum > right_sum:
12                dp[i] = max(dp[i], dp[j] + left_sum)
13            elif left_sum < right_sum:
14                dp[i] = max(dp[i], dp[j] + right_sum)
15            else:
16                dp[i] = max(dp[i], dp[j] + left_sum, dp[j] + right_sum)
17    return dp[-1]

Complexity note: The time complexity remains O(n²) due to the nested loops for calculating scores from splits, but we use O(n) space for the DP array and prefix sums, which optimizes our calculations.

  • 1Dynamic programming helps avoid recalculating overlapping subproblems.
  • 2Using prefix sums allows for efficient sum calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.