| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.StoneGame2; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class StoneGame2DynamicProgramming : IStoneGame2 |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n^3) |
| | | 19 | | /// Space complexity - O(n^2) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="piles"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public int StoneGameII(int[] piles) |
| | 4 | 24 | | { |
| | 4 | 25 | | var n = piles.Length; |
| | | 26 | | |
| | 4 | 27 | | var dp = new int[n][]; |
| | | 28 | | |
| | 44 | 29 | | for (var i = 0; i < n; i++) |
| | 18 | 30 | | { |
| | 18 | 31 | | dp[i] = new int[n + 1]; |
| | 18 | 32 | | } |
| | | 33 | | |
| | 4 | 34 | | var suffixSum = new int[n]; |
| | | 35 | | |
| | 4 | 36 | | suffixSum[n - 1] = piles[n - 1]; |
| | | 37 | | |
| | 36 | 38 | | for (var i = n - 2; i >= 0; i--) |
| | 14 | 39 | | { |
| | 14 | 40 | | suffixSum[i] = suffixSum[i + 1] + piles[i]; |
| | 14 | 41 | | } |
| | | 42 | | |
| | 44 | 43 | | for (var i = n - 1; i >= 0; i--) |
| | 18 | 44 | | { |
| | 232 | 45 | | for (var m = 1; m <= n; m++) |
| | 98 | 46 | | { |
| | 98 | 47 | | if (i + (2 * m) >= n) |
| | 82 | 48 | | { |
| | 82 | 49 | | dp[i][m] = suffixSum[i]; |
| | 82 | 50 | | } |
| | | 51 | | else |
| | 16 | 52 | | { |
| | 116 | 53 | | for (var x = 1; x <= 2 * m; x++) |
| | 42 | 54 | | { |
| | 42 | 55 | | dp[i][m] = Math.Max(dp[i][m], suffixSum[i] - dp[i + x][Math.Max(m, x)]); |
| | 42 | 56 | | } |
| | 16 | 57 | | } |
| | 98 | 58 | | } |
| | 18 | 59 | | } |
| | | 60 | | |
| | 4 | 61 | | return dp[0][1]; |
| | 4 | 62 | | } |
| | | 63 | | } |