question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
stone-game-v
|
Beats 60.00%of users with JavaScript
|
beats-6000of-users-with-javascript-by-ss-hvj9
|
\n# Code\n\nvar stoneGameV = function(stoneValue) {\n let n = stoneValue.length;\n const pre = new Array(n + 1).fill(0);\n for (let i = 1; i <= n; i++) {\n
|
SSDeepakReddy
|
NORMAL
|
2023-10-14T05:32:22.145488+00:00
|
2023-10-14T05:32:22.145514+00:00
| 56 | false |
\n# Code\n```\nvar stoneGameV = function(stoneValue) {\n let n = stoneValue.length;\n const pre = new Array(n + 1).fill(0);\n for (let i = 1; i <= n; i++) {\n pre[i] = pre[i - 1] + stoneValue[i - 1];\n }\n const dp = [...Array(n).fill(null)].map((_) => new Array(n).fill(0));\n for (let l = 1; l < n; l++) {\n for (let i = 0; i < n - l; i++) {\n let j = i + l,\n res = 0;\n for (let k = i; k < j; k++) {\n let left = pre[k + 1] - pre[i],\n right = pre[j + 1] - pre[k + 1];\n if (left < right) {\n res = Math.max(res, left + dp[i][k]);\n } else if (left > right) {\n res = Math.max(res, right + dp[k + 1][j]);\n } else {\n res = Math.max(res, left + dp[i][k]);\n res = Math.max(res, right + dp[k + 1][j]);\n }\n }\n dp[i][j] = res;\n }\n }\n return dp[0][n - 1];\n};\n```
| 1 | 0 |
['JavaScript']
| 0 |
stone-game-v
|
Basic Java Solution(Commented)
|
basic-java-solutioncommented-by-karthik_-r5nd
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Karthik_1512
|
NORMAL
|
2023-09-16T17:16:11.484621+00:00
|
2023-09-16T17:16:11.484644+00:00
| 140 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int findSum(int[] stoneValue)\n {\n int sum=0;\n for(int n:stoneValue) sum+=n;\n return sum; // returns the sum of the stoneValue Array.\n }\n public int findMin(int[] stoneValue,int start,int end,int preSum,int sum,int[][] dp)\n {\n if(start==end) return 0; // returns 0 whenever the length of the array equals 1.\n\n if(dp[start][end]!=-1) return dp[start][end]; // returns the stored value of the sub problem when the specific values of start and end already solved before.\n\n int ans=Integer.MIN_VALUE; // Initializing the required maximum score of alice with the minimum possible integer.\n\n for(int i=start;i<end;i++) // Iterating a for loop from the starting index to the ending index to check with all the possible partitions.\n {\n preSum=preSum+stoneValue[i]; //Increment the preSum with value of stoneValue at current index where we are going to make partition.\n\n if(preSum < sum-preSum)\n {\n ans=Math.max(ans,preSum+findMin(stoneValue,start,i,0,preSum,dp)); \n //if the preSum(the sum of the array from start index to current index) is less than the remaining part of the array,\n //Then Bob throws away the right array i.e the array with the largest sum,\n //Alice score is increased by preSum(sum of the left array) and parameters of the left array are sent to the recursion.\n }\n else if(preSum>sum-preSum)\n {\n ans=Math.max(ans,sum-preSum+findMin(stoneValue,i+1,end,0,sum-preSum,dp));\n //if the preSum(the sum of the array from start index to current index) is more than the remaining part of the array,\n //Then Bob throws away the left array i.e the array with the largest sum,\n //Alice score is increased by sum-preSum(sum of the right array) and parameters of the right array are sent to the recursion.\n }\n else{\n ans=Math.max(ans,Math.max(preSum+findMin(stoneValue,start,i,0,preSum,dp),sum-preSum+findMin(stoneValue,i+1,end,0,sum-preSum,dp)));\n // if the preSum(the sum of left array) and sum-preSum(the sum of the right array) are equal,\n // Then, Bob gives Alice a chance to remove either the left array or the right array,\n // So alice has a chance to get maximum score from either of the arrays,\n // So Alice take the the Max value from both the recursions(recursion calls of both left array and right array).\n }\n }\n return dp[start][end]=ans; // store the value of the partition for specific start and end values in the dp array.\n }\n public int stoneGameV(int[] stoneValue) {\n int sum = findSum(stoneValue); // To find Sum of the stoneValue array.\n\n int[][] dp = new int[stoneValue.length][stoneValue.length]; // A 2D array for memorization.\n\n for(int i=0;i<stoneValue.length;i++)\n {\n Arrays.fill(dp[i],-1); // Initializing all the values of the 2D array dp with -1.\n }\n return findMin(stoneValue,0,stoneValue.length-1,0,sum,dp); // function to find Maximum score of alice.\n }\n}\n```\n**Thank You : )**
| 1 | 0 |
['Dynamic Programming', 'Recursion', 'Memoization', 'Prefix Sum', 'Java']
| 1 |
stone-game-v
|
Python O(n^2) DP Solution, faster than 100%(1399ms)
|
python-on2-dp-solution-faster-than-10013-cf6a
|
\n\'\'\'\nSuppose we know the k\' for stones[i..j], what do we know about k\' for stones[i..j+1]? It is either the same or it got shifted a few places to the ri
|
hemantdhamija
|
NORMAL
|
2022-10-16T07:53:06.184473+00:00
|
2022-10-16T07:53:06.184514+00:00
| 846 | false |
```\n\'\'\'\nSuppose we know the k\' for stones[i..j], what do we know about k\' for stones[i..j+1]? It is either the same or it got shifted a few places to the right.\nAnd so if we calculate dp values in the order: dp[i][i], dp[i][i+1], dp[i][i+2], ..., dp[i][j], we can essentially keep track of k\' as we go within that same linear time bound.\n\nUsing this idea, we implement the final solution. Couple of pointers about my code:\n\n1) mid: represents k\' or first index such that left half >= right half\n2) with i < j, max[i][j] represents left[i][j] of previous solution i.e. max(dp[i][i], dp[i][i+1], dp[i][i+2] .. dp[i][j]) and max[j][i] represents right[i][j] of previous solution i.e. max(dp[i][j], dp[i+1][j], dp[i+2][j] .. dp[j][j]). We could have used two different arrays left and right just like previous solution but this trick saves space.\n3) I am traversing in the order: dp[j][j], dp[j-1,j], dp[j-2, j], .., dp[i][j] instead of the above mentioned order but the idea remains same.\n\'\'\'\n\nclass Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n sz = len(stoneValue)\n dp, maxScore = [[0] * sz for _ in range(sz)], [[0] * sz for _ in range(sz)]\n for i in range(sz):\n maxScore[i][i] = stoneValue[i]\n for j in range(1, sz):\n mid, sm, rightHalf = j, stoneValue[j], 0\n for i in range(j - 1, -1, -1):\n sm += stoneValue[i]\n while (rightHalf + stoneValue[mid]) * 2 <= sm:\n rightHalf += stoneValue[mid]\n mid -= 1\n dp[i][j] = maxScore[i][mid] if rightHalf * 2 == sm else (0 if mid == i else maxScore[i][mid - 1]);\n dp[i][j] = max(dp[i][j], 0 if mid == j else maxScore[j][mid + 1])\n maxScore[i][j] = max(maxScore[i][j - 1], dp[i][j] + sm);\n maxScore[j][i] = max(maxScore[j][i + 1], dp[i][j] + sm);\n return dp[0][sz - 1]\n```
| 1 | 1 |
['Dynamic Programming', 'Memoization', 'Python', 'Python3']
| 0 |
stone-game-v
|
Simple Partition DP | Recursive | Memoization
|
simple-partition-dp-recursive-memoizatio-2vj5
|
We need to try out all possible partition for every subproblem hence partition dp.\n\tBase Case: When there is only one element left in subarray (i.e i == j) we
|
lrrajput2001
|
NORMAL
|
2022-09-08T13:05:06.769420+00:00
|
2022-09-08T13:05:50.037944+00:00
| 395 | false |
We need to try out all possible partition for every subproblem hence **partition dp**.\n\t**Base Case:** When there is only one element left in subarray (i.e i == j) we return 0 because alice cannot score anything from that.\n```\nint f(int i,int j,vector<int> &stoneValue,vector<vector<int>> &dp){\n if(i == j) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n int totSum = 0;\n for(int k = i ; k <= j ; k++) totSum += stoneValue[k];\n int leftSum = 0;\n int res = INT_MIN;\n for(int k = i ; k < j ; k++){\n leftSum += stoneValue[k];\n int rightSum = totSum - leftSum;\n if(leftSum == rightSum){\n int dropLeft = rightSum + f(k+1,j,stoneValue,dp);\n int dropRight = leftSum + f(i,k,stoneValue,dp);\n res = max(res,max(dropLeft,dropRight));\n }\n else if(leftSum < rightSum) res = max(res,leftSum + f(i,k,stoneValue,dp));\n else res = max(res,rightSum + f(k+1,j,stoneValue,dp));\n }\n return dp[i][j] = res;\n }\n int stoneGameV(vector<int>& stoneValue) {\n int n = stoneValue.size();\n vector<vector<int>> dp(n,vector<int> (n,-1));\n return f(0,n-1,stoneValue,dp);\n }\n```
| 1 | 0 |
['Dynamic Programming', 'Recursion', 'Memoization', 'C']
| 0 |
stone-game-v
|
c++
|
c-by-rony_the_loser-iqt7
|
(```) class Solution {\npublic:\n \n int dp[501][501];\n \n int help(vector& v, int start, int end)\n {\n if(start > end) \n {
|
Algo_wizard2020
|
NORMAL
|
2022-08-27T18:38:41.015707+00:00
|
2022-08-27T18:38:41.015740+00:00
| 37 | false |
(```) class Solution {\npublic:\n \n int dp[501][501];\n \n int help(vector<int>& v, int start, int end)\n {\n if(start > end) \n {\n return 0;\n }\n \n int sum = 0, left_sum = 0, right_sum =0,ans = 0;\n \n if(dp[start][end] != -1)\n {\n return dp[start][end];\n }\n \n for(int i=start; i<=end; i++)\n {\n sum += v[i];\n }\n \n for(int j=start; j<=end; j++)\n {\n left_sum += v[j];\n \n right_sum = sum - left_sum;\n \n if(left_sum < right_sum)\n {\n ans = max(ans,left_sum + help(v,start,j));\n }\n else if(left_sum > right_sum)\n {\n ans = max(ans, right_sum + help(v,j+1,end));\n }\n else\n {\n ans = max(ans,left_sum + help(v,start,j));\n ans = max(ans, right_sum + help(v,j+1,end));\n \n }\n \n }\n \n return dp[start][end] = ans;\n }\n \n int stoneGameV(vector<int>& stoneValue) \n {\n \n memset(dp,-1,sizeof(dp));\n \n return help(stoneValue, 0, stoneValue.size()-1);\n \n \n }\n};
| 1 | 0 |
[]
| 0 |
stone-game-v
|
[C++] || DP || Check Every possible Partition
|
c-dp-check-every-possible-partition-by-r-gmm6
|
\nclass Solution {\npublic:\n int dp[501][501] ;\n int solve(vector<int>&nums , int s , int e){\n if(s == e) return 0 ; \n if(dp[s][e] != -1
|
rahul921
|
NORMAL
|
2022-07-13T13:27:01.106070+00:00
|
2022-07-13T13:36:17.826639+00:00
| 181 | false |
```\nclass Solution {\npublic:\n int dp[501][501] ;\n int solve(vector<int>&nums , int s , int e){\n if(s == e) return 0 ; \n if(dp[s][e] != -1) return dp[s][e] ;\n \n int sum = 0 , left = 0 , right = 0 ;\n for(int i = s ; i <= e ; ++i) sum += nums[i] ;\n \n int op1 = 0 , op2 = 0 ;\n for(int i = s ; i < e ; ++i ){\n left += nums[i] , right = sum - left ;\n if(left <= right) op1 = max(op1,left + solve(nums,s,i)) ;\n if(left >= right) op2 = max(op2,right + solve(nums,i+1,e)) ;\n }\n \n return dp[s][e] = max(op1,op2) ;\n }\n int stoneGameV(vector<int>& nums) {\n memset(dp,-1,sizeof(dp)) ;\n return solve(nums,0,nums.size() - 1) ;\n }\n};\n```
| 1 | 0 |
['C']
| 0 |
stone-game-v
|
Worst case time complexity when using recursion without DP
|
worst-case-time-complexity-when-using-re-o0nl
|
I was able to solve this problem using DP in O(n^2) time + top down approach.\n\nBut wasnt able to do satisfactory time complexity analysis when only using recu
|
pritamprakash
|
NORMAL
|
2022-07-03T11:19:18.244161+00:00
|
2022-07-03T11:19:18.244219+00:00
| 73 | false |
I was able to solve this problem using DP in O(n^2) time + top down approach.\n\nBut wasnt able to do satisfactory time complexity analysis when only using recursion without using any DP?\n\nHas anyone done time complexity analysis when only using recusrsion without any DP ?
| 1 | 0 |
['Recursion']
| 0 |
stone-game-v
|
C++ solution. || Recursion+Memoization.
|
c-solution-recursionmemoization-by-samar-yrvw
|
\n#define ll long long\n#define vb vector<bool>\n#define vi vector<int>\n#define vl vector<long long>\n#define vvb vector<vector<bool>>\n#define vvi vector<vect
|
samarthya2912
|
NORMAL
|
2022-06-07T03:20:08.151053+00:00
|
2022-06-07T03:20:08.151084+00:00
| 87 | false |
```\n#define ll long long\n#define vb vector<bool>\n#define vi vector<int>\n#define vl vector<long long>\n#define vvb vector<vector<bool>>\n#define vvi vector<vector<int>>\n#define vvl vector<vector<long long>>\n#define pii pair<int,int>\n#define all(i) i.begin(),i.end()\n#define f(i,s,e) for(int i = s; i < e; i++)\n#define b(i,s,e) for(int i = s; i >= e; i--)\ninline int getMid(int i,int j) { return i+(j-i)/2; }\n\nclass Solution {\npublic:\n vi prefixSum;\n\n int maxScore(int i, int j, vvi& memo) {\n if(i == j) return 0;\n if(memo[i][j] != -1) return memo[i][j];\n\n int ans = 0;\n f(k,i,j) {\n int left = prefixSum[k+1]-prefixSum[i], right = prefixSum[j+1]-prefixSum[k+1];\n if(left > right) ans = max(ans,right+maxScore(k+1,j,memo));\n else if(left < right) ans = max(ans,left+maxScore(i,k,memo));\n else ans = max({ans,left+maxScore(i,k,memo),right+maxScore(k+1,j,memo)});\n }\n return memo[i][j] = ans; \n }\n\n int stoneGameV(vi& stoneValue) {\n int n = stoneValue.size();\n this->prefixSum = vi(n+1);\n prefixSum[0] = stoneValue[0];\n f(i,1,n+1) prefixSum[i] = prefixSum[i-1]+stoneValue[i-1];\n vvi memo(n,vi(n,-1));\n return maxScore(0,n-1,memo);\n }\n};\n```
| 1 | 0 |
[]
| 0 |
stone-game-v
|
ONLY GO SOLUTION | DP (only using indices)
|
only-go-solution-dp-only-using-indices-b-nmih
|
```\nfunc stoneGameV(stoneValue []int) int {\n type Key struct {\n r int\n l int\n }\n prefix := []int{0}\n curr := 0\n for _, s :=
|
Pedraamy
|
NORMAL
|
2022-04-20T22:52:30.618025+00:00
|
2022-04-20T23:03:32.602933+00:00
| 79 | false |
```\nfunc stoneGameV(stoneValue []int) int {\n type Key struct {\n r int\n l int\n }\n prefix := []int{0}\n curr := 0\n for _, s := range stoneValue {\n curr += s\n prefix = append(prefix, curr)\n }\n memo := make(map[Key]int)\n var dp func(lb int, rb int) int\n dp = func(lb int, rb int) int {\n if rb == lb {\n return 0\n }\n currKey := Key{lb, rb}\n val, exists := memo[currKey]\n if exists {\n return val\n }\n var res, curr, sl, sr int\n res = 0\n for i := lb; i < rb; i++ {\n sl = prefix[i]-prefix[lb-1]\n sr = prefix[rb]-prefix[i]\n if sl < sr {\n curr = sl+dp(lb, i)\n } else if sl > sr {\n curr = sr+dp(i+1, rb)\n } else {\n curr = Max2(sl+dp(lb, i), sr+dp(i+1, rb))\n }\n res = Max2(res, curr)\n }\n memo[currKey] = res\n return res\n }\n return dp(1, len(prefix)-1)\n}\n\nfunc Max2(c1 int, c2 int) int {\n if c2 > c1 {\n return c2\n } else {\n return c1\n }\n}
| 1 | 0 |
[]
| 0 |
stone-game-v
|
CPP/Game Theory/Highly Commented/Step-by-step/Easy Approach/N2
|
cppgame-theoryhighly-commentedstep-by-st-hps1
|
\nclass Solution {\npublic:\n int dp[501][501];\n \n// Time Complexity : O(N2)\n// Idea is to check \n// from i ...... j\n// parition the
|
vijaypal1621
|
NORMAL
|
2022-03-14T15:16:01.853726+00:00
|
2022-03-14T15:20:50.429739+00:00
| 101 | false |
```\nclass Solution {\npublic:\n int dp[501][501];\n \n// Time Complexity : O(N2)\n// Idea is to check \n// from i ...... j\n// parition the array[i...j] from k = [i to (j-1)]\n// forming two parts arr[i...k] and arr[k+1 .... j]\n// check whichever is greater, discard and recur for smaller part\n \n vector<int> pre;\n int solve(int i,int j,vector<int>&v )\n {\n if(i==j)return 0;\n \n int &x = dp[i][j];\n if(x != -1)return x;\n \n // just to calculate the total sum of array [i....j]\n int total = pre[j+1]-pre[i];\n \n int leftPartSum = 0; // to ccalculate the array sum [i...k]\n int rightPartSum;\n int ans = 0;// final ans to be returned\n for(int k=i;k<j;k++){\n leftPartSum += v[k];// adding the kth el\n rightPartSum = total - leftPartSum;\n if(leftPartSum > rightPartSum){ // if left part is greater, dicard left and recur for right part\n ans = max(ans,rightPartSum + solve(k+1,j,v) );\n }else if(leftPartSum < rightPartSum){// if right part is greater, discard right part and recur for left part\n ans = max(ans,leftPartSum + solve(i,k,v));\n }else{\n // both part have equal sum\n ans = max(ans, leftPartSum + solve(i,k,v));// recur for left\n ans = max(ans, rightPartSum + solve(k+1,j,v));// recur for right\n }\n }\n return x = ans;\n \n }\n \n \n int stoneGameV(vector<int>& v) {\n memset(dp,-1,sizeof(dp));\n int sum = 0;\n pre.push_back(0);\n for(int i=0;i<v.size();i++){\n sum += v[i];\n pre.push_back(sum);\n // cout << pre[i] << " ";\n }\n \n int ans = solve(0,v.size()-1,v);\n return ans;\n }\n};\n```
| 1 | 0 |
['Dynamic Programming', 'Prefix Sum']
| 0 |
stone-game-v
|
Do Only What is stated in the question | Noob Solution | Game Strategy
|
do-only-what-is-stated-in-the-question-n-ssfb
|
```\nclass Solution {\npublic:\n vector> dp;\n int fun(int i,int j,vector &arr,vector &pre){\n //Base Case \n if(i == j) return 0;\n
|
njcoder
|
NORMAL
|
2022-03-06T11:32:19.617434+00:00
|
2022-03-06T11:32:44.638667+00:00
| 115 | false |
```\nclass Solution {\npublic:\n vector<vector<int>> dp;\n int fun(int i,int j,vector<int> &arr,vector<int> &pre){\n //Base Case \n if(i == j) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n int score = INT_MIN;\n for(int part = i+1;part <= j;part++){\n int left = pre[part-1] - (i == 0 ? 0 : pre[i-1]);\n int right = pre[j] - pre[part-1];\n if(left > right){\n score = max(score,right + fun(part,j,arr,pre)); \n }else if(left < right){\n score = max(score,left + fun(i,part-1,arr,pre));\n }else{\n score = max(score,left + fun(i,part-1,arr,pre)); \n score = max(score,right + fun(part,j,arr,pre)); \n }\n }\n return dp[i][j] = score;\n \n }\n \n int stoneGameV(vector<int>& arr) {\n int n = arr.size();\n \n vector<int> pre(n);\n pre[0] = arr[0];\n for(int i=1;i<n;i++) pre[i] = pre[i-1] + arr[i];\n dp = vector<vector<int>> (n,vector<int> (n,-1));\n return fun(0,n-1,arr,pre);\n }\n};
| 1 | 0 |
['Recursion', 'Memoization']
| 1 |
stone-game-v
|
[C++/DP and Memorization] 172 ms (94.32%) , 10.6 MB (75.68%) O(n^2)
|
cdp-and-memorization-172-ms-9432-106-mb-ds10f
|
The following algorithm is an 1-index solution.\nFirst a DP table is defined as\ndp[i][j] := the maximum score with the initial states: stones in the range from
|
HirofumiTsuda
|
NORMAL
|
2021-08-18T11:41:57.569137+00:00
|
2021-08-20T14:58:55.966878+00:00
| 172 | false |
The following algorithm is an 1-index solution.\nFirst a DP table is defined as\ndp[i][j] := the maximum score with the initial states: stones in the range from i to j (i and j are included).\nThen, there are (j - i) stones in this state. It means there are (j - i - 1) separators.\nIt is clear that the value dp[i][j] is found if all ways of setting a separator is investigated.\nTo accelerate computation, each derived value should be memorized.\n\n```\nclass Solution {\npublic:\n #define MAX 500\n int memo[MAX+2][MAX+2]; // 1-index\n int sum[MAX+2];\n int dp(int i, int j){\n if(i == j)\n return 0;\n if(memo[i][j] > 0)\n return memo[i][j];\n int ans=0;\n for(int n=i;n<j;n++){\n int left = sum[n] - sum[i-1];\n int right = sum[j] - sum[n];\n int tmp;\n if(left < right){\n tmp = dp(i,n) + left;\n }else if(right < left){\n tmp = dp(n+1, j)+right;\n }else{\n int lnum = dp(i,n);\n int rnum = dp(n+1,j);\n tmp = max(lnum, rnum) + right;\n }\n if(ans < tmp)\n ans = tmp;\n }\n memo[i][j] = ans;\n return ans;\n }\n \n int stoneGameV(vector<int>& stoneValue) {\n int N = stoneValue.size();\n int amt= 0;\n for(int i=0;i<N;i++){\n amt += stoneValue[i];\n sum[i+1] = amt;\n }\n for(int i=0;i<N-1;i++){\n memo[i+1][i+2] = min(stoneValue[i], stoneValue[i+1]);\n }\n return dp(1,N);\n }\n};\n```
| 1 | 0 |
[]
| 0 |
stone-game-v
|
Simple C++ Dynamic Programming Solution
|
simple-c-dynamic-programming-solution-by-f135
|
\nclass Solution {\npublic:\n \n int dp[505][505];\n \n int fun(vector<int>& stoneValue, int i, int j){\n \n if(i == j){\n
|
tanishqj2005
|
NORMAL
|
2021-07-20T17:47:05.237864+00:00
|
2021-07-20T17:47:05.237907+00:00
| 98 | false |
```\nclass Solution {\npublic:\n \n int dp[505][505];\n \n int fun(vector<int>& stoneValue, int i, int j){\n \n if(i == j){\n return 0;\n }\n \n if(dp[i][j] != -1){\n return dp[i][j];\n }\n \n int sum = 0, curr = 0, ans = 0;\n \n for(int k = i; k <= j; k++){\n sum += stoneValue[k];\n }\n \n for(int k = i; k < j; k++){\n \n curr += stoneValue[k];\n \n if(curr < (sum - curr)){\n ans = max(ans,fun(stoneValue,i,k) + curr);\n }\n else if(curr > (sum - curr)){\n ans = max(ans,fun(stoneValue,k+1,j) + (sum - curr));\n }\n else{\n ans = max(ans, curr + max(fun(stoneValue,i,k),fun(stoneValue,k+1,j)));\n }\n \n }\n \n dp[i][j] = ans;\n \n return ans;\n \n }\n \n int stoneGameV(vector<int>& stoneValue) {\n \n int size = stoneValue.size();\n memset(dp,-1,sizeof(dp));\n \n return fun(stoneValue,0,size-1);\n }\n};\n\n```
| 1 | 0 |
[]
| 0 |
stone-game-v
|
Top down DP | Commented
|
top-down-dp-commented-by-apooos3-297p
|
\nclass Solution {\n public int stoneGameV(int[] s) {\n int n = s.length;\n\t\t//prefix array so that difference between left and right can be calcula
|
apooos3
|
NORMAL
|
2021-06-11T18:59:12.892598+00:00
|
2021-06-11T19:02:59.100933+00:00
| 312 | false |
```\nclass Solution {\n public int stoneGameV(int[] s) {\n int n = s.length;\n\t\t//prefix array so that difference between left and right can be calculated in O(1)\n int[] prefix = new int[n];\n\t\t//2D DP array for each cut (length) vs. elements containing the actual sum\n int[][] dp = new int[n][n];\n prefix[0] = s[0];\n for(int i=1; i<n; i++) {\n prefix[i] = prefix[i-1] + s[i];\n }\n \n return minimax5(s, prefix, 0, n-1, dp);\n }\n\n private int minimax5(int[] stones, int[] pre, int s, int e, int[][] dp) {\n\t\t//base case: no profit as game ends when there\'s only one stone left\n if(s==e) {\n return 0;\n }\n\t\t//return the memoized solution\n if(dp[s][e]!=0) return dp[s][e];\n int sum = 0, ans = Integer.MIN_VALUE;\n\t\t//make a cut at each length and find the one with maximum profit\n for(int i=s; i<e; i++) {\n int left = s == 0? 0 : pre[s-1];\n\t\t\t//calculate left and right sum at the cut using prefix array built earlier\n int pl = pre[i] - left; int pr = pre[e] - pre[i];\n sum = Math.min(pl, pr);\n \n\t\t\t//pick the one with lower value as the larger one will be thrown\n\t\t\t//in case of equal partition, we need to look both ways and find the one that returns maximum value\n if(pl>pr) {\n sum += minimax5(stones, pre, i+1, e, dp);\n }else if(pl<pr) {\n sum += minimax5(stones, pre, s, i, dp);\n }else{\n sum += \n Math.max(minimax5(stones, pre, i+1, e, dp), minimax5(stones, pre, s, i, dp));\n }\n //save the overall maximum\n ans = Math.max(ans, sum);\n }\n //memoize the answer and return\n return dp[s][e]=ans;\n }\n}\n```\n\nHowever, I am not sure what would be it\'s time complexity (seems O(n^3) but not sure). If anyone can explain, that\'d be very helpful.
| 1 | 0 |
['Dynamic Programming', 'Memoization', 'Java']
| 0 |
stone-game-v
|
DP n^3 with optimisation and elimination. Detailed explanation. [Latest] [Python]
|
dp-n3-with-optimisation-and-elimination-isryp
|
The idea of elimiation was based on GP and inspired from @Prezes Code. In O(n^3) we trim some corner cases. Like if we are itterating over different partionions
|
glastonbury
|
NORMAL
|
2021-06-04T19:46:12.451498+00:00
|
2021-06-04T19:49:35.265342+00:00
| 155 | false |
The idea of elimiation was based on GP and inspired from @Prezes Code. In O(n^3) we trim some corner cases. Like if we are itterating over different partionions for a given subarray(start,end) we keep track of what is the max from any given subarry. Now when we compute leftRow Sum and rightRow sum we apply an elimation logic. Let\'s sat leftRow was smaller and got selected for next round . Now what is the maxValue we can get from left Row in best case scenario? So lets say the sum of leftRow is X. So X will be directly added to points. But what is the maximum value possible from this X in remaining rounds without actually checking? It will be when X splits equally in two X/2 and X/2 and bob removes X/2 and adds the other X/2 to points, which further goes for next round (X/2 that remained) and in best case splits in X/4 and X/4 and bob will removes one X/4 and other X/4 will go to your point and similarly it goes on.. So the best case points will be X +X/2 +X/4 +X/8 +X/16 = X/(1-1/2) = X/(1/2) =2X. \nSo for any distribution of X, the remaining sum wont go beyond this. We compare this with current max. If it is less than current max then in now that sub partition can form a sum more than max.\nSo we compare- if 2*(sumOfSlectedRow)<=max then skip\nTime - worst case may go upto n^3 but average case will be much much better. 76% faster than others\nMemory - O(n^2) beats 95%\n```\nclass Solution:\n def stoneGameV(self, sv: List[int]) -> int:\n n=len(sv)\n sv.append(0)\n for i in range(n-1,-1,-1):\n sv[i]+=sv[i+1]\n #sv now stores the sum. sv[i]= sum of all stones from ith postion to end \n \n @lru_cache(None)\n def getMax(startIndex,endIndex):\n # We start solving a subProblem as to maximum score alice can get for subarray from startIndex to endIndex\n \n #if start==end that means only one element left in subarray. You can only get zero. like for [6] \n # you will make pile [6] and[0] and bob will remove [6] leaving you with zero\n if (endIndex==startIndex):\n return 0\n \n # Now we start making partitons. Remember- Having one row empty will be useless as it will give zero\n # lets say startIndex=3 and endIndex is 6, So we itterate over partions as :\n # [3] [4,5,6]; [3,4] [5,6]; [3,4,5] [6]. So leftRow will contain startIndex to ith element\n # Also note we do not incude endIndexin loop as it would cause right row to be empty\n for i in range(startIndex,endIndex):\n \n left=[startIndex,i]\n right=[i+1,endIndex]\n \n #we wont calculate sum each time. Rather use precomputed sum array to get sum from i to j in 0(1)\n leftSum=sv[startIndex]-sv[i+1]\n rightSum=sv[i+1]-sv[endIndex+1]\n \n # min(leftSum,rightSum) represents the sum of row that is selected.\n # Now calue you can get from it will be sum + sum/2 + sum/4 .... = 2*sum\n # if this is less than currentMax , then it can never form next max. So skip\n # i>startIndex is just to check if it is the first element we are starting or if there is a previous max\n if i>startIndex and 2*min(leftSum,rightSum)<maxi:\n continue\n if leftSum>rightSum:\n last=getMax(right[0],right[1])\n value=rightSum+last\n elif rightSum>leftSum:\n last=getMax(left[0],left[1])\n value=leftSum+last\n else :\n last=getMax(right[0],right[1])\n value=max(leftSum+getMax(left[0],left[1]),rightSum+getMax(right[0],right[1]))\n \n # if we have a previous max Value compare it with it. If greater so we have find a new partion for\n # given subarray that gives more points to alice\n if i>startIndex:\n maxi=max(maxi,value)\n else:\n maxi=value\n result = maxi \n return result\n \n \n return getMax(0,n-1)\n```
| 1 | 1 |
[]
| 0 |
stone-game-v
|
Recursion ->DP
|
recursion-dp-by-sinhaneha455-cm9x
|
TLE Error Recursion Code\n\n public int solve(int si , int ei , int[]arr){\n \n if(si>ei){\n return 0;\n }\n \n in
|
sinhaneha455
|
NORMAL
|
2021-05-11T12:59:44.921023+00:00
|
2021-05-11T13:00:20.543162+00:00
| 311 | false |
**TLE Error Recursion Code**\n```\n public int solve(int si , int ei , int[]arr){\n \n if(si>ei){\n return 0;\n }\n \n int rightPart =0 , leftPart=0 , result=0;\n \n for(int i=si;i<=ei;i++){\n rightPart+=arr[i];\n }\n \n for(int i=si;i<ei;i++){\n leftPart+=arr[i];\n rightPart-=arr[i];\n \n \n // bob will throw maximum one so we need to add the leftpart in our result\n if(leftPart<rightPart)result = Math.max(result , leftPart+solve(si , i , arr));\n // bob will throw maximum one so we need to add the rightpart in our result\n if(leftPart>rightPart)result = Math.max(result , rightPart+solve(i+1, ei , arr)); \n //if both are equal then alice will decide which need to be thrown \n if(leftPart==rightPart) result = Math.max(result , leftPart + Math.max(solve(si , i , arr) , solve(i+1 , ei , arr)));\n \n \n \n }\n \n return result;\n }\n```\n\n\n**Dp Top down **\n\n\n```\n public int solve(int si , int ei , int[]arr , int[][] strg){\n \n if(si>ei){\n return 0;\n }\n if(strg[si][ei]!=-1){\n return strg[si][ei];\n }\n int rightPart =0 , leftPart=0 , result=0;\n \n for(int i=si;i<=ei;i++){\n rightPart+=arr[i];\n }\n \n for(int i=si;i<ei;i++){\n leftPart+=arr[i];\n rightPart-=arr[i];\n \n \n // bob will throw maximum one so we need to add the leftpart in our result\n if(leftPart<rightPart)result = Math.max(result , leftPart+solve(si , i , arr , strg));\n // bob will throw maximum one so we need to add the rightpart in our result\n if(leftPart>rightPart)result = Math.max(result , rightPart+solve(i+1, ei , arr , strg)); \n //if both are equal then alice will decide which need to be thrown \n if(leftPart==rightPart) result = Math.max(result , leftPart + Math.max(solve(si , i , arr , strg) , solve(i+1 , ei , arr , strg)));\n \n \n \n }\n strg[si][ei]=result;\n return result;\n }\n```\n
| 1 | 0 |
['Dynamic Programming', 'Recursion', 'Java']
| 0 |
stone-game-v
|
C# solution using Memoization and Prefix Sum
|
c-solution-using-memoization-and-prefix-psz82
|
\npublic class Solution {\n int[,] dp;\n int[] prefix;\n public int Solve(int[] arr, int i, int j)\n {\n if(i>=j) return 0;\n if(dp[i,
|
aj936563
|
NORMAL
|
2021-05-08T11:10:30.118437+00:00
|
2021-05-08T11:10:30.118465+00:00
| 56 | false |
```\npublic class Solution {\n int[,] dp;\n int[] prefix;\n public int Solve(int[] arr, int i, int j)\n {\n if(i>=j) return 0;\n if(dp[i,j]!=0) return dp[i,j];\n int res = 0;\n for(int k=i;k<=j;k++)\n {\n int left = prefix[k+1] - prefix[i];\n int right = prefix[j+1] - prefix[k+1];\n if(left>right)\n {\n res = Math.Max(res, right + Solve(arr,k+1,j));\n }\n else if(left<right)\n {\n res = Math.Max(res, left + Solve(arr,i,k));\n }\n else\n {\n res = Math.Max(res, right + Math.Max(Solve(arr,i,k),Solve(arr,k+1,j)));\n }\n \n }\n \n dp[i,j] = res;\n return res;\n \n }\n public int StoneGameV(int[] stoneValue) {\n int n = stoneValue.Count();\n dp = new int[n,n];\n prefix = new int[n+1];\n prefix[0] = 0;\n for(int i=0;i<n;i++)\n {\n prefix[i+1] = prefix[i] + stoneValue[i];\n }\n return Solve(stoneValue,0,n-1);\n }\n}\n```
| 1 | 0 |
[]
| 0 |
stone-game-v
|
100% (T), 100%(S) :: C / Python - Memoization
|
100-t-100s-c-python-memoization-by-tuhin-lmm6
|
Down below, you\'ll find C and Python implementations for the same. Funny how a 100% faster C solution exceeds the allotted time limit when coded in Python, The
|
tuhinnn_py
|
NORMAL
|
2021-05-06T15:09:39.632686+00:00
|
2021-05-06T15:09:39.632717+00:00
| 254 | false |
Down below, you\'ll find C and Python implementations for the same. Funny how a 100% faster C solution exceeds the allotted time limit when coded in Python, The code is pretty self explanatory. Let me know if you still need help in the comments below.\n\n**C**\n\n```\nint dp[501][501];\n\nint max(int a, int b)\n{\n return (a > b)? a: b;\n}\n\nint playGame(int* sumValue, int* arr, int i, int j)\n{\n if(dp[i][j] != -1)\n return dp[i][j];\n if(i == j)\n {\n dp[i][j] = 0;\n return 0;\n }\n int res, k, ans = 0;\n for(k = i; k < j; k++)\n {\n int left = sumValue[k + 1] - sumValue[i], right = sumValue[j + 1] - sumValue[k + 1];\n if(left > right)\n res = right + playGame(sumValue, arr, k + 1, j); \n else if(left < right)\n res = left + playGame(sumValue, arr, i, k); \n else\n res = max(left + playGame(sumValue, arr, i, k), right + playGame(sumValue, arr, k + 1, j)); \n ans = max(ans, res);\n }\n dp[i][j] = ans;\n return ans;\n}\n\nint stoneGameV(int* stoneValue, int stoneValueSize)\n{\n memset(dp, -1, sizeof(dp));\n if(stoneValueSize == 1)\n return 0;\n \n int i;\n int* sumValue = (int*)malloc(sizeof(int) * (stoneValueSize + 1));\n sumValue[0] = 0;\n sumValue[1] = stoneValue[0];\n \n for(i = 1; i < stoneValueSize; i++)\n sumValue[i + 1] = sumValue[i] + stoneValue[i];\n \n return playGame(sumValue, stoneValue, 0, stoneValueSize - 1);\n}\n```\n\n**Python**\n\n```\nfrom functools import lru_cache\nclass Solution:\n def stoneGameV(self, arr: List[int]) -> int:\n if len(arr) == 1:\n return 0\n \n sumValue = [0, arr[0]]\n for i in range(1, len(arr)):\n sumValue.append(sumValue[-1] + arr[i])\n \n @lru_cache(None)\n def playGame(i, j):\n if i == j:\n return 0\n ans = 0\n for k in range(i, j):\n left, right = sumValue[k + 1] - sumValue[i], sumValue[j + 1] - sumValue[k + 1] \n # sum(arr[i: k + 1]), sum(arr[k + 1: j + 1])\n if left > right:\n res = right + playGame(k + 1, j) \n elif left < right:\n res = left + playGame(i, k) \n else:\n res = max(left + playGame(i, k), right + playGame(k + 1, j)) \n ans = max(ans, res)\n return ans\n return playGame(0, len(arr) - 1)\n```
| 1 | 0 |
['Memoization', 'C', 'Python']
| 1 |
stone-game-v
|
80ms C++ DP and reduce branches
|
80ms-c-dp-and-reduce-branches-by-mz1007-veqv
|
The key to accelerate the code is to reduce branches (if(2*min(sumL, sumR) < tmp) continue;), which helps to reduce runtime from 800ms to 80ms (faster than 97%)
|
mz1007
|
NORMAL
|
2021-03-29T14:14:43.637621+00:00
|
2021-03-30T18:38:10.513341+00:00
| 152 | false |
The key to accelerate the code is to reduce branches (`if(2*min(sumL, sumR) < tmp) continue;`), which helps to reduce runtime from 800ms to 80ms (faster than 97%).\n```c++\nclass Solution {\npublic:\n int stoneGameV(vector<int>& v) {\n //dp[i][j]: max scores obtained from v[i:j]\n //dp[i][j] = max{ ( sum(v[i:k]) < sum(v[k+1:j]) ) ? sum(v[i:k]) + dp[i][k] : sum(v[k+1:j]) + dp[k+1][j] } for k in [i,j-1]\n int n = v.size();\n if(n == 1) return 0;\n vector<int> sum(n, 0);\n int lsum = 0;\n for(int i = 0; i < n; i++) sum[i] = lsum = lsum + v[i];\n vector<vector<int>> dp(n, vector<int>(n, 0));\n function<int(int,int)> helper = [&](int i, int j){ \n if(i == j) return 0;\n if(dp[i][j]) return dp[i][j];\n int tmp = 0;\n int init = i > 0 ? sum[i-1] : 0; //careful\n for(int k = i; k <= j-1; k++){ //careful about range of k\n int sumL = sum[k] - init;\n int sumR = sum[j] - sum[k];\n if(2*min(sumL, sumR) < tmp) continue; //key to reduce the runtime: 2*min(sumL, sumR) is the score upper bound for this cut (reduce runtime from 800ms to 80ms)\n if(sumL != sumR) tmp = max(tmp, (sumL<sumR) ? sumL + helper(i,k) : sumR + helper(k+1,j));\n else tmp = max(tmp, max(sumL + helper(i,k), sumR + helper(k+1,j)));\n }\n return dp[i][j] = tmp;\n };\n return helper(0, n-1);\n }\n};\n\n```
| 1 | 0 |
[]
| 2 |
stone-game-v
|
Javascript beats 100% time and 100% memory (368ms, 39.4mb)
|
javascript-beats-100-time-and-100-memory-lysu
|
\nvar stoneGameV = function(stones) {\n let bestAns = 0\n let stoneSum = stones.reduce((sum, current)=> {return sum+ current},0)\n\n function splitAndA
|
raphyhayes
|
NORMAL
|
2021-03-22T20:18:35.767200+00:00
|
2021-03-22T20:30:35.880266+00:00
| 135 | false |
```\nvar stoneGameV = function(stones) {\n let bestAns = 0\n let stoneSum = stones.reduce((sum, current)=> {return sum+ current},0)\n\n function splitAndAdd(stoneSum, ans, leftBound,rightBound){\n\t\n if (rightBound === leftBound){return ans}\n\n if (rightBound - leftBound === 1){\n return ans + Math.min(stones[leftBound], stones[rightBound])\n }\n let bestSoFar = 0\n let leftSum = 0\n let rightSum = stoneSum\n for(let i = leftBound; i <= rightBound; i++){\n leftSum += stones[i]\n rightSum -=stones[i]\n \n \n if (2* Math.min(leftSum, rightSum) + ans < bestAns){continue} \n if (leftSum === rightSum){\n bestSoFar = Math.max(splitAndAdd(leftSum, ans+leftSum, leftBound,i), bestSoFar)\n bestSoFar = Math.max(splitAndAdd(rightSum, ans+rightSum, i+1, rightBound), bestSoFar)\n \n } else{\n \n leftSum > rightSum\n ? bestSoFar = Math.max(splitAndAdd(rightSum, ans+rightSum, i+1, rightBound),bestSoFar)\n : bestSoFar = Math.max(splitAndAdd(leftSum, ans+leftSum, leftBound, i), bestSoFar)\n }\n \n }\n \n bestAns = Math.max(bestAns, bestSoFar)\n return bestSoFar\n }\n \n \n let ans = splitAndAdd(stoneSum, 0, 0, stones.length-1)\n return ans\n \n};\n```
| 1 | 0 |
['JavaScript']
| 1 |
stone-game-v
|
C++ Solution [Recursive Memoization ]
|
c-solution-recursive-memoization-by-sha_-nxh8
|
\nclass Solution {\npublic:\n \n vector<int> presum;\n \n vector<vector<int>> dp;\n \n vector<int> stones;\n \n int solve(int i,int j)\n
|
sha_256
|
NORMAL
|
2021-01-07T07:08:28.336630+00:00
|
2021-01-07T07:08:28.336664+00:00
| 110 | false |
```\nclass Solution {\npublic:\n \n vector<int> presum;\n \n vector<vector<int>> dp;\n \n vector<int> stones;\n \n int solve(int i,int j)\n {\n \n\n\n if(i>j)\n return 0;\n\n \n if(i == j)\n return 0;\n \n \n if(j-i == 1)\n {\n return min(stones[i],stones[j]);\n }\n \n if(dp[i][j]!=-1)\n return dp[i][j];\n \n int ans = 0;\n \n \n for(int k = i;k<j;k++)\n {\n \n \n int pre_;\n \n if(i-1 <0)\n {\n pre_ = 0;\n }\n else\n {\n pre_ = presum[i-1];\n }\n \n if(presum[k]-pre_>presum[j]-presum[k])\n {\n int temp = solve(k+1,j);\n int x_ = presum[j]-presum[k];\n ans = max(ans,temp+x_);\n }\n else if(presum[k]-pre_<presum[j]-presum[k])\n {\n int temp = solve(i,k);\n int x_ = presum[k]-pre_;\n ans = max(ans,temp+x_);\n }\n else\n {\n \n int temp1 = solve(k+1,j)+presum[j]-presum[k];\n int temp2 = solve(i,k)+presum[k]-pre_;\n ans = max(ans,max(temp1,temp2));\n \n } \n \n }\n return dp[i][j] = ans;\n }\n \n \n \n int stoneGameV(vector<int>& stoneValue) {\n \n \n \n dp.resize(stoneValue.size()+1,vector<int>(stoneValue.size()+1,-1));\n presum.resize(stoneValue.size(),0);\n stones = stoneValue;\n \n presum[0] = stoneValue[0]; \n for(int i = 1;i<stoneValue.size();i++)\n {\n presum[i] = presum[i-1]+stoneValue[i];\n }\n \n \n return solve(0,stoneValue.size()-1);\n }\n};\n```
| 1 | 0 |
[]
| 0 |
stone-game-v
|
C++ | DP | ft. Prefix - Sum | Clean Code.
|
c-dp-ft-prefix-sum-clean-code-by-lekhesh-syum
|
\n\nclass Solution {\npublic:\n int dp[501][501];\n int prefixSum[501];\n \n int helper(vector<int>& s, int l, int r){\n \n if(l >= r)
|
lekhesh12
|
NORMAL
|
2020-10-26T18:03:31.100195+00:00
|
2020-10-26T18:03:31.100248+00:00
| 116 | false |
\n```\nclass Solution {\npublic:\n int dp[501][501];\n int prefixSum[501];\n \n int helper(vector<int>& s, int l, int r){\n \n if(l >= r) return 0; // BASE case\n \n if(dp[l][r] != -1)return dp[l][r]; // Return pre commputed sub-problem.\n \n int ans = INT_MIN;\n \n for(int i = 0; i < r-l; i++){ // You can only break the array at l+0, l+1, l+2,.....r-1 th index.\n \n int L = prefixSum[l+i+1] - prefixSum[l];\n int R = prefixSum[r+1] - prefixSum[l+i+1];\n \n if(L < R){\n int temp = dp[l][l+i] == -1 ? helper(s, l, l+i) : dp[l][l+i];\n ans = max(ans, L + temp);\n }\n else if (R < L){\n int temp = dp[l+i+1][r] == -1 ? helper(s, l + i + 1, r) : dp[l+i+1][r];\n ans = max(ans, temp + R);\n }\n else{\n int temp1 = dp[l][l+i] == -1 ? helper(s, l, l+i) : dp[l][l+i];\n int temp2 = dp[l+i+1][r] == -1 ? helper(s, l + i + 1, r) : dp[l+i+1][r];\n ans = max(ans, L + max(temp1, temp2));\n }\n }\n return dp[l][r] = ans;\n }\n \n \n int stoneGameV(vector<int>& stoneValue) {\n int ans = INT_MIN;\n memset(dp, -1, sizeof dp);\n int n = stoneValue.size();\n \n prefixSum[0] = 0; // Prefix sum is used to optimize the intermediate Range Sum...\n \n for(int i = 0; i < n; i++)prefixSum[i+1] = prefixSum[i] + stoneValue[i];\n \n ans = helper(stoneValue, 0, n - 1);\n \n return ans;\n }\n};\n```\n
| 1 | 0 |
[]
| 0 |
stone-game-v
|
Java solution from brute-force to DP O(n^3)
|
java-solution-from-brute-force-to-dp-on3-gbyg
|
Solution brute-force - Time Limit Exceeded \n\npublic class StoneGameVRecursiveApproach {\n public static void main(String[] args) {\n int[] stoneGame
|
akiramonster
|
NORMAL
|
2020-10-04T22:37:44.193620+00:00
|
2020-10-04T22:37:44.193664+00:00
| 99 | false |
Solution brute-force - Time Limit Exceeded \n```\npublic class StoneGameVRecursiveApproach {\n public static void main(String[] args) {\n int[] stoneGame = {6, 2, 3, 4, 5, 5};\n System.out.println(stoneGameV(stoneGame));\n }\n\n public static int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length;\n int[] sum = createPrefixSum(stoneValue);\n return stoneGameV(0, n - 1, sum);\n }\n\n private static int stoneGameV(int i, int k, int[] sum) {\n if (i >= k) return 0;\n int maxScore = Integer.MIN_VALUE;\n for (int j = i; j < k; j++) { // divides to 2 rows (i, j), (j+1, k)\n int sum1 = sum[j + 1] - sum[i]; // sum from i -> j inclusive\n int sum2 = sum[k + 1] - sum[j + 1]; // sum from j+1 -> k inclusive\n if (sum1 > sum2) { // Bob removes left\n maxScore = Math.max(maxScore, stoneGameV(j + 1, k, sum) + sum2);\n } else if (sum1 < sum2) { // Bob removes right\n maxScore = Math.max(maxScore, stoneGameV(i, j, sum) + sum1);\n } else { // Bob let Alice to decide which rows will be removed.\n maxScore = Math.max(maxScore, Math.max(stoneGameV(i, j, sum), stoneGameV(j + 1, k, sum)) + sum1);\n }\n }\n return maxScore;\n }\n\n private static int[] createPrefixSum(int[] stoneValue) {\n int n = stoneValue.length;\n int[] sum = new int[n + 1];\n for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + stoneValue[i];\n return sum;\n }\n}\n\n```\n\nSolution uses memoization\n```\npublic class StoneGameVMemoizationApproach {\n public static void main(String[] args) {\n int[] stoneGame = {6, 2, 3, 4, 5, 5};\n System.out.println(stoneGameV(stoneGame));\n }\n\n public static int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length;\n int[] sum = createPrefixSum(stoneValue);\n int[][] memo = new int[n][n];\n stoneGameV(0, n - 1, sum, memo);\n return memo[0][n - 1];\n }\n\n private static int stoneGameV(int i, int k, int[] sum, int[][] memo) {\n if (i >= k) return 0;\n if (memo[i][k] > 0) return memo[i][k];\n int maxScore = Integer.MIN_VALUE;\n for (int j = i; j < k; j++) { // divides to 2 rows (i, j), (j+1, k)\n int sum1 = sum[j + 1] - sum[i]; // sum from i -> j inclusive\n int sum2 = sum[k + 1] - sum[j + 1]; // sum from j+1 -> k inclusive\n if (sum1 > sum2) { // Bob removes left\n maxScore = Math.max(maxScore, stoneGameV(j + 1, k, sum, memo) + sum2);\n } else if (sum1 < sum2) { // Bob removes right\n maxScore = Math.max(maxScore, stoneGameV(i, j, sum, memo) + sum1);\n } else { // Bob let Alice to decide which rows will be removed.\n maxScore = Math.max(maxScore, Math.max(stoneGameV(i, j, sum, memo), stoneGameV(j + 1, k, sum, memo)) + sum1);\n }\n }\n memo[i][k] = maxScore;\n return maxScore;\n }\n\n private static int[] createPrefixSum(int[] stoneValue) {\n int n = stoneValue.length;\n int[] sum = new int[n + 1];\n for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + stoneValue[i];\n return sum;\n }\n}\n```\n\nSolution uses DP Bottom-up\n```\n\npublic class StoneGameVBottomUpApproach {\n public static void main(String[] args) {\n int[] stoneGame = {6, 2, 3, 4, 5, 5};\n System.out.println(stoneGameV(stoneGame));\n }\n\n public static int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length;\n int[] sum = createPrefixSum(stoneValue);\n int[][] dp = new int[n][n];\n for (int i = n - 1; i >= 0; i--) {\n for (int k = 0; k < n; k++) {\n if (i >= k) continue;\n dp[i][k] = Integer.MIN_VALUE;\n for (int j = i; j < k; j++) { // divides to 2 rows (i, j), (j+1, k)\n int sum1 = sum[j + 1] - sum[i]; // sum from i -> j inclusive\n int sum2 = sum[k + 1] - sum[j + 1]; // sum from j+1 -> k inclusive\n if (sum1 > sum2) { // Bob removes left\n dp[i][k] = Math.max(dp[i][k], dp[j + 1][k] + sum2);\n } else if (sum1 < sum2) { // Bob removes right\n dp[i][k] = Math.max(dp[i][k], dp[i][j] + sum1);\n } else { // Bob let Alice to decide which rows will be removed.\n dp[i][k] = Math.max(dp[i][k], Math.max(dp[i][j], dp[j + 1][k]) + sum1);\n }\n }\n }\n }\n return dp[0][n - 1];\n }\n\n private static int[] createPrefixSum(int[] stoneValue) {\n int n = stoneValue.length;\n int[] sum = new int[n + 1];\n for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + stoneValue[i];\n return sum;\n }\n}\n```\nReference: https://leetcode.com/problems/stone-game-v/discuss/870497/Java-Recursive-greater-Memoization-greater-2D-Bottom-Up\n
| 1 | 0 |
[]
| 0 |
stone-game-v
|
Over-commented code for Stone Game V (1563)
|
over-commented-code-for-stone-game-v-156-bi2b
|
Hopefully this helps some folks. Over-commented :-)\n\nclass Solution {\npublic:\n int sgv( int b, /* Beginning index of row of stone
|
tktripathy
|
NORMAL
|
2020-09-10T02:16:53.689418+00:00
|
2020-09-10T02:23:44.386236+00:00
| 148 | false |
Hopefully this helps some folks. Over-commented :-)\n```\nclass Solution {\npublic:\n int sgv( int b, /* Beginning index of row of stones */\n int e, /* Ending index of row */\n vector<int>& s, /* Original row of stones - prefix-summed */\n vector<vector<int>>& memo) /* Memo to not TLE */\n {\n int m/*ax score*/ = 0;\n \n /* Return if we have seen this answer from before */\n if (memo[b][e] != -1) return memo[b][e];\n\n for (int i = b; i < e; i++) {\n int t = 0;\n /* \n * Alice divides the row into two different rows -\n * left (b - i) and right (i+1 - e). Bob now calculates\n * total sums using precomputed prefix sums.\n */\n int l = s[i] - (b ? s[b - 1] : 0);\n int r = s[e] - s[i]; \n if (l == r) { /* Alice gets a chance to pick. So, here she\n * evaluates both rows for max possible score.\n */\n t = l + /* Score Alice has now */\n max(sgv(b, i, s, memo), /* Score from recursion on left row */\n sgv(i+1, e, s, memo));/* Score from recursion on right row */\n } else if (l > r ) { /* Bob throws away left row */\n t = r + /* Score Alice has now - right row sum */ \n sgv(i+1, e, s, memo); /* Score from recursion on the right row */\n } else { /* Bob throws away right row */\n t = l + /* Score Alice has now - left row sum */\n sgv(b, i, s, memo); /* Score from recursion on the left row */\n }\n m = max(m, t); /* The max score that Alice can get */\n }\n \n /* Remember the max score that Alice can get if \n * she has a row of stones beginning at b and \n * ending in e\n */\n return memo[b][e] = m;\n }\n \n int stoneGameV(vector<int>& s) {\n vector<vector<int>> memo(501, vector<int>(501, -1));\n for (int i = 1; i < s.size(); i++) s[i] += s[i-1]; /* prefix sum */\n return sgv(0, s.size() - 1, s, memo);\n }\n};\n```
| 1 | 0 |
[]
| 1 |
stone-game-v
|
[Python] Need help with TLE | DP O(n^3)
|
python-need-help-with-tle-dp-on3-by-zhen-ue2b
|
126/131 cases passed. I used lru to cache results from function. \n\nclass Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n # stoneVa
|
zhenglun
|
NORMAL
|
2020-09-01T03:25:39.446560+00:00
|
2020-09-01T03:25:39.446605+00:00
| 269 | false |
126/131 cases passed. I used lru to cache results from function. \n```\nclass Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n # stoneValue\n prefix = [0] \n for v in stoneValue:\n prefix.append(prefix[-1]+v)\n @lru_cache(None)\n def dp(i, j):\n if i == j:\n return 0\n val = 0\n for cut in range(i, j):\n l, r = prefix[cut+1] - prefix[i], prefix[j+1] - prefix[cut+1]\n if l > r:\n val = max(val, r+dp(cut+1, j))\n elif l < r:\n val = max(val, l+dp(i, cut))\n else:\n val = max(val, l+dp(i, cut), r+dp(cut+1, j))\n return val\n return dp(0, len(stoneValue)-1)\n```
| 1 | 0 |
['Python']
| 1 |
stone-game-v
|
[Java] Easy Bottom Up O(N^3)
|
java-easy-bottom-up-on3-by-lancewang-fra5
|
```\n\npublic int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length;\n int[] sum = new int[n + 1];\n \n for(int i = 0; i <
|
lancewang
|
NORMAL
|
2020-08-30T03:28:31.326601+00:00
|
2020-08-30T03:43:35.741919+00:00
| 86 | false |
```\n\npublic int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length;\n int[] sum = new int[n + 1];\n \n for(int i = 0; i < n; i++){\n sum[i+1] = sum[i] + stoneValue[i];\n }\n \n int[][] dp = new int[n + 1][n + 1];\n \n for(int len = 2; len <= n; len++){\n for(int i = 0; i + len <= n; i++){\n int j = i + len;\n \n for(int k = i + 1; k < j; k++){\n int left = sum[k] - sum[i];\n int right = sum[j] - sum[k];\n \n if(left <= right){\n dp[i][j] = Math.max(dp[i][j], left + dp[i][k]);\n }\n \n if(right <= left){\n dp[i][j] = Math.max(dp[i][j], right + dp[k][j]);\n }\n }\n }\n }\n \n return dp[0][n];\n }\n\t
| 1 | 0 |
[]
| 0 |
stone-game-v
|
well comment and easy to understand..
|
well-comment-and-easy-to-understand-by-f-26z3
|
We are going to explore all the devisior of stoneValue and maintain a sum...\nat any position there could be 3 condition\n1.leftsum is greater then right sum\n\
|
faltu_admi
|
NORMAL
|
2020-08-29T05:07:26.349298+00:00
|
2020-08-29T05:07:26.349348+00:00
| 125 | false |
We are going to explore all the devisior of stoneValue and maintain a sum...\nat any position there could be 3 condition\n1.leftsum is greater then right sum\n\tin this case bob will through out left part and alice got the point as right sum and rest of game start with right part of stoneValue\n2.right sum is greater then left sum\n\tin this case bob will through out right part and alice got the point as left sum and rest of game start with left part of stoneValue\n3.both are equal\n\tlet\'s play the alice as both above 1 and 2 condition and decide which one is better\n```\nint solve( vector<int> &sum ,int **dp, int left , int right ){\n\tif(left>right) return 0;//invalid interavel\n\tint &ans=dp[left][right];\n\tif(ans!=-1) return ans;\n\tfor(int i=left ; i<=right ; i++){\n\t\tint leftSum=sum[i]-sum[left-1];//get the left sum and get the right sum\n\t\tint rightSum=sum[right]-sum[i];\n\t\tif(leftSum>rightSum){\n\t\t\t//left sum will be through out\n\t\t\tans=max(ans , rightSum+solve(sum, dp ,i+1 ,right));\n\t\t}else if(leftSum<rightSum){\n\t\t\t//right sum will be through out\n\t\t\tans=max(ans , leftSum+solve(sum, dp , left , i));\n\t\t}else{\n\t\t\t//let\'s find both way\n\t\t\tans=max(ans , max(rightSum+solve(sum ,dp, i+1 , right) , leftSum+solve(sum ,dp, left , i)));\n\t\t}\n\t}\n\treturn ans;\n}\nint stoneGameV(vector<int>& stoneValue) {\n\tint n=stoneValue.size();\n\tvector<int> sum(n+1);\n\tint **dp=new int*[n+1];\n\tsum[0]=0;\n\tfor(int i=0 ; i<=n;i++){\n\t\tdp[i]=new int[n+1];\n\t\tif(i) sum[i]=sum[i-1]+stoneValue[i-1];\n\t\tfor(int j=0 ; j<=n ; j++) dp[i][j]=-1;\n\t}\n\treturn solve(sum,dp ,1 , stoneValue.size());\n}\n```\nHappy coding!!!
| 1 | 0 |
[]
| 0 |
stone-game-v
|
Easy JAVA dp solution
|
easy-java-dp-solution-by-virti-4co0
|
\nclass Solution {\n Integer dp[][];\n public int stoneGameV(int[] stoneValue) {\n dp=new Integer[stoneValue.length][stoneValue.length];\n f
|
virti
|
NORMAL
|
2020-08-24T16:07:17.295591+00:00
|
2020-08-24T16:07:54.527030+00:00
| 109 | false |
```\nclass Solution {\n Integer dp[][];\n public int stoneGameV(int[] stoneValue) {\n dp=new Integer[stoneValue.length][stoneValue.length];\n for(int i=1;i<stoneValue.length;i++) stoneValue[i]+=stoneValue[i-1];\n return check(0,stoneValue.length-1,stoneValue);\n }\n public int check(int i, int j, int arr[]){\n if(dp[i][j]!=null) return dp[i][j];\n if(i>=j) return dp[i][j]=0;\n int ans=0,b=(i==0)?0:arr[i-1];\n for(int a=i;a<j;a++){\n int c=arr[j]-arr[a];\n if(c>arr[a]-b) ans=Math.max(ans, arr[a]-b+check(i,a,arr));\n else if(c<arr[a]-b) ans=Math.max(ans, c+check(a+1,j,arr));\n else ans=Math.max(arr[a]-b+check(i,a,arr),c+check(a+1,j,arr));\n }\n return dp[i][j]=ans;\n }\n}\n```\n
| 1 | 0 |
['Dynamic Programming']
| 0 |
stone-game-v
|
easy DP solution using cumulative sum (JAVA)
|
easy-dp-solution-using-cumulative-sum-ja-0em4
|
\nclass Solution {\n public int stoneGameV(int[] stoneValue) {\n int n= stoneValue.length;\n if(n==1) return 0;\n int A[]= new int[n+1];
|
nrjain1997
|
NORMAL
|
2020-08-24T12:31:39.869105+00:00
|
2020-08-24T12:31:39.869153+00:00
| 83 | false |
```\nclass Solution {\n public int stoneGameV(int[] stoneValue) {\n int n= stoneValue.length;\n if(n==1) return 0;\n int A[]= new int[n+1];\n int dp[][] = new int[n+1][n+1];\n for(int[] x:dp)Arrays.fill(x,-1);\n A[0]=0;\n for(int i=1;i<n+1;i++) A[i]=A[i-1]+stoneValue[i-1];\n System.out.println(Arrays.toString(A)); \n return dfs(dp,0,n-1,A,stoneValue); \n }\n public int dfs(int dp[][],int i, int j,int A[],int arr[]){\n if(j<=i) return dp[i][j]=0;\n if(dp[i][j]!=-1) return dp[i][j]; \n int max =Integer.MIN_VALUE;\n for(int k=i+1;k<=j;k++){\n int left =A[k]-A[i];\n int right = A[j+1]-A[k];\n int a;\n if(left<right)\n a =left+dfs(dp,i,k-1,A,arr);\n else if(right<left)\n a =right+dfs(dp,k,j,A,arr);\n else\n a=left+ Math.max(dfs(dp,i,k-1,A,arr),dfs(dp,k,j,A,arr)); \n max= Math.max(a,max); \n }\n dp[i][j]=max;\n return dp[i][j];\n }\n}\n```
| 1 | 0 |
['Dynamic Programming', 'Prefix Sum']
| 0 |
stone-game-v
|
DP Javascript
|
dp-javascript-by-rockwell153-kjaf
|
\n/**\n:subproblem\n what is the maximum score of the rest of the stones\n\n:recurrence\n for all possible break points\n if equal halfs\n
|
rockwell153
|
NORMAL
|
2020-08-23T18:04:55.021498+00:00
|
2020-08-23T18:05:04.633135+00:00
| 113 | false |
```\n/**\n:subproblem\n what is the maximum score of the rest of the stones\n\n:recurrence\n for all possible break points\n if equal halfs\n dp[left][right] = max(\n leftsum + recur( left ),\n rightsum + recur( right )\n )\n else \n dp[left][right] = max( dp, recur( min( left, right ) ) )\n \n return dp[left][right]\n */\nvar stoneGameV = function(a) {\n const rowSum = getRowSumWithNums( a )\n const dp = Array.from({length:a.length+1},_=>Array(a.length+1).fill(0))\n const guess = ( left, right ) => {\n if ( left === right ) return 0\n if ( dp[ left ][ right ] ) return dp[ left ][ right ]\n\n for ( let i = left + 1; i <= right; i++ ) {\n const leftSum = rowSum( left, i - 1 )\n const rightSum = rowSum( i, right )\n\n if ( leftSum === rightSum ) {\n dp[ left ][ right ] = Math.max(\n dp[ left ][ right ],\n leftSum + guess( left, i - 1 ),\n rightSum + guess( i, right )\n )\n } else if ( rightSum > leftSum ) {\n dp[ left ][ right ] = Math.max(\n dp[ left ][ right ],\n leftSum + guess( left, i - 1 )\n )\n } else {\n dp[ left ][ right ] = Math.max(\n dp[ left ][ right ],\n rightSum + guess( i, right )\n )\n }\n }\n \n return dp[ left ][ right ]\n }\n guess( 0, a.length-1 )\n \n return dp[ 0 ][ a.length-1 ]\n}\n\nconst getRowSumWithNums = nums => {\n const sums = nums.reduce( ( s, x ) => [ ...s, x + ( s[s.length - 1 ] || 0 ) ], [] )\n\n return ( left, right ) => sums[ right ] - ( sums[ left - 1 ] || 0 )\n}\n```
| 1 | 0 |
['Dynamic Programming', 'JavaScript']
| 0 |
stone-game-v
|
C# Prefix Sum + Memoization
|
c-prefix-sum-memoization-by-ve7545-uz17
|
Runtime: 228 ms\nMemory Usage: 33.7 MB\n\n public int StoneGameV(int[] stoneValue) {\n int[,] dp = new int[stoneValue.Length, stoneValue.Length];
|
ve7545
|
NORMAL
|
2020-08-23T15:43:23.240503+00:00
|
2020-08-23T15:57:00.697791+00:00
| 77 | false |
Runtime: 228 ms\nMemory Usage: 33.7 MB\n```\n public int StoneGameV(int[] stoneValue) {\n int[,] dp = new int[stoneValue.Length, stoneValue.Length]; \n int[] prefixSum = new int[stoneValue.Length+1];\n \n for(int i=0; i< stoneValue.Length; i++)\n {\n prefixSum[i+1] = prefixSum[i] + stoneValue[i];\n }\n \n return Traverse(stoneValue, 0, stoneValue.Length-1, dp, prefixSum);\n }\n \n private int Traverse(int[] stoneValue, int start, int end, int[,] dp, int[] prefixSum)\n { \n if (start >= end) { return 0; }\n if (dp[start,end] != 0) { return (dp[start,end]==-1)? 0 : dp[start,end]; }\n \n int total = prefixSum[end+1] - prefixSum[start];\n \n int left =0;\n int right;\n int result = -1;\n \n for(int i=start; i < end; i++)\n {\n left = prefixSum[i+1] - prefixSum[start];\n right = total - left;\n \n if (left >= right)\n {\n result = Math.Max(result, right + Traverse(stoneValue, i+1, end, dp, prefixSum));\n }\n \n if (left <= right)\n {\n result = Math.Max(result, left + Traverse(stoneValue, start, i, dp, prefixSum));\n }\n }\n \n dp[start, end] = result;\n return result;\n }\n```\n\nSecond way of doing this but it takes much longer to execute:\n\nRuntime: 1328 ms\nMemory Usage: 33.5 MB\n```\n\n public int StoneGameV(int[] stoneValue) {\n int[,] dp = new int[stoneValue.Length, stoneValue.Length];\n \n int[] prefixSum = new int[stoneValue.Length+1];\n \n for(int i=0; i< stoneValue.Length; i++)\n {\n dp[i,i] = 0;\n prefixSum[i+1] = prefixSum[i] + stoneValue[i];\n }\n \n for(int k=1; k< stoneValue.Length; k++)\n {\n for(int i=0; i + k < stoneValue.Length; i++)\n {\n Traverse(stoneValue, i, i+k, dp, prefixSum);\n }\n }\n \n return dp[0, stoneValue.Length-1];\n }\n \n private int Traverse(int[] stoneValue, int start, int end, int[,] dp, int[] prefixSum)\n { \n int total = prefixSum[end+1] - prefixSum[start];\n \n int left =0;\n int right;\n int result = 0;\n \n for(int i=start; i < end; i++)\n {\n left = prefixSum[i+1] - prefixSum[start];\n right = total - left;\n \n if (left >= right)\n {\n result = Math.Max(result, right + dp[i+1,end]);\n }\n \n if (left <= right)\n {\n result = Math.Max(result, left + dp[start, i]);\n }\n }\n \n dp[start, end] = result;\n return result;\n }
| 1 | 0 |
[]
| 1 |
stone-game-v
|
please clear my doubt
|
please-clear-my-doubt-by-anshuman2043-bwbr
|
\nclass Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n ans = 0\n def game(l,score):\n #print(l)\n #pri
|
Anshuman2043
|
NORMAL
|
2020-08-23T09:06:05.966531+00:00
|
2020-08-23T09:06:05.966562+00:00
| 136 | false |
```\nclass Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n ans = 0\n def game(l,score):\n #print(l)\n #print(score)\n if len(l) <= 1:\n nonlocal ans\n ans = max((ans,score))\n return\n s = sum(l)\n x = 0\n for i in range(len(l)):\n x += l[i]\n if x == s/2:\n game(l[:i+1],score+x)\n game(l[i+1:],score+x)\n return\n elif x >s/2:\n game(l[i+1:],score+s-x)\n game(l[:i],score+x-l[i])\n return \n game(stoneValue,0)\n return ans\n \n```\n\nhere is my greedy approch for this Question.\nmy approch is as follow \n\n1. i first find the element, that add to either side of the array gives the sum greater than or equal to half of the sum of initial array.\n2. then there are two path now , either we choose first half or we choose second half .\n3. we compare the result for each such possiblity and return maximum of them \n\nmy ans for arr = [98 ,77 ,24 ,49 ,6 ,12 ,2 ,44 ,51 ,96] is 307\nbut expected ans is 330\n\nis have checked my ans many times but i can\'t find any way to get the ans (score) 330.\ni thought ans is wrong\ncan you help me out how the ans is 330.\n
| 1 | 0 |
[]
| 1 |
stone-game-v
|
TopDownDFS+Memo(O(N^3)) And BottomUpDP(O(N^2))
|
topdowndfsmemoon3-and-bottomupdpon2-by-j-xomg
|
Top Down DFS + Memo 460ms\ncpp\nclass Solution {\n vector<int> prefixSum;\n vector<vector<int>> mem;\n int cnt = 0;\n void dfs(const vector<int>& pr
|
jiah
|
NORMAL
|
2020-08-23T08:05:35.198352+00:00
|
2020-08-23T08:09:33.253435+00:00
| 123 | false |
Top Down DFS + Memo 460ms\n```cpp\nclass Solution {\n vector<int> prefixSum;\n vector<vector<int>> mem;\n int cnt = 0;\n void dfs(const vector<int>& prefixSum, int begin, int end) {\n if (mem[begin][end])\n return;\n if (begin+1 == end)\n return;\n cnt ++;\n int ans = 0;\n int total = prefixSum[end] - prefixSum[begin];\n if (end - begin >= 2) {\n for (int mid = begin+1; mid < end; mid++) {\n int left = prefixSum[mid] - prefixSum[begin];\n int right = total - left;\n int tmp = 0;\n if (left < right) {\n tmp += left;\n dfs(prefixSum, begin, mid);\n tmp += mem[begin][mid];\n } else if (left > right) {\n tmp += right;\n dfs(prefixSum, mid, end);\n tmp += mem[mid][end];\n } else {\n tmp += left;\n dfs(prefixSum, begin, mid);\n dfs(prefixSum, mid, end);\n tmp += max(mem[begin][mid], mem[mid][end]);\n }\n ans = max(ans, tmp);\n }\n } \n mem[begin][end] = ans;\n }\npublic:\n int stoneGameV(vector<int>& stoneValue) {\n cout << stoneValue.size() << endl;\n int n = stoneValue.size();\n prefixSum.resize(n+1);\n mem.resize(n+1, vector<int>(n+1));\n for (int i = 0; i < n; i++)\n prefixSum[i+1] = prefixSum[i] + stoneValue[i];\n dfs(prefixSum, 0, stoneValue.size());\n cout << cnt << endl; // See how many states visited if you want to know why O(n^3) topdown works\n return mem[0][n];\n }\n};\n```\n\nBottom Up DP 200+ms\n```cpp\nclass Solution {\npublic:\n int stoneGameV(vector<int>& stoneValue) {\n const int n = stoneValue.size();\n vector<int> ps(n+1); // prefix_sum\n vector<vector<int>> dp(n+1, vector<int>(n+1));\n vector<vector<int>> maxL = dp;\n vector<vector<int>> maxR = dp;\n vector<vector<int>> mid = dp;\n \n for (int i = 0; i < n; i++)\n ps[i+1] = ps[i] + stoneValue[i];\n \n for (int i = 0; i <= n; i++) {\n int middle = i+1;\n for (int j = i+2; j <= n; j++) {\n while (middle < j && \n ps[middle] - ps[i] <= ps[j] - ps[middle]) {\n middle ++;\n }\n mid[i][j] = middle-1;\n }\n }\n \n for (int i = 0; i < n; i++)\n maxL[i][i+1] = maxR[i][i+1] = stoneValue[i];\n \n for (int i = n; i >= 0; i--) {\n for (int j = i+2; j <= n; j++) {\n int middle = mid[i][j];\n if (ps[middle] - ps[i] < ps[j] - ps[middle]) {\n dp[i][j] = max(maxL[i][middle], maxR[middle+1][j]);\n } else {\n dp[i][j] = max(maxL[i][middle], maxR[middle][j]);\n }\n maxL[i][j] = max(maxL[i][j-1], dp[i][j] + ps[j] - ps[i]);\n maxR[i][j] = max(maxR[i+1][j], dp[i][j] + ps[j] - ps[i]);\n }\n }\n return dp[0][n];\n }\n};\n```\n\n
| 1 | 0 |
[]
| 0 |
stone-game-v
|
Prefix Sum +DP(Memoization)
|
prefix-sum-dpmemoization-by-ghoshashis54-db68
|
\nint cache[505][505];\nint pre[505];\nint n;\nint dp(int left,int right)\n{\n if(left == right)\n return 0;\n int &ans = cache[left][right];\n
|
ghoshashis545
|
NORMAL
|
2020-08-23T08:00:39.298549+00:00
|
2020-08-23T08:00:39.298593+00:00
| 102 | false |
```\nint cache[505][505];\nint pre[505];\nint n;\nint dp(int left,int right)\n{\n if(left == right)\n return 0;\n int &ans = cache[left][right];\n if(ans != -1)\n return ans;\n // left subarray -> [left , partition_index]\n // right subarray -> [partition_index + 1 , right]\n \n for(int partition_index = left ; partition_index < right; ++partition_index)\n {\n int leftsum = pre[partition_index];\n if(left > 0)\n leftsum -= pre[left-1];\n \n int rightsum = pre[right] - pre[partition_index];\n \n // if leftsum value greater than rightsum than bob throw away left subarray([left,partition_index]) and rightsum value will added to answer and do following step using right subarray([partition_index+1,right]).\n \n if(leftsum > rightsum)\n ans = max(ans, rightsum + dp(partition_index+1 , right));\n \n else if(leftsum < rightsum)\n ans = max(ans ,leftsum + dp(left , partition_index));\n // if leftsum equal to rightsum than we go both subarray seperately.\n else\n {\n ans = max(ans , rightsum + dp(partition_index+1 , right));\n ans = max(ans , leftsum + dp(left , partition_index));\n }\n }\n return ans;\n \n}\nclass Solution {\npublic:\n int stoneGameV(vector<int>& a) {\n n = a.size();\n // initialize\n for(int i = 0;i<n;++i)\n {\n for(int j =0;j<n;++j)\n cache[i][j]=-1;\n pre[i] =0;\n }\n\t\t// build prefix\n for(int i = 0;i < n;++i)\n {\n if(i > 0)\n pre[i]+=pre[i-1];\n pre[i]+=a[i];\n }\n \n return dp(0,n-1);\n \n }\n};\n```\nTime : O(n^3)\nSpace : O(n^2)
| 1 | 0 |
[]
| 2 |
stone-game-v
|
Python PrefixSum + DFS memo
|
python-prefixsum-dfs-memo-by-ysz951-7s79
|
\nclass Solution(object):\n def stoneGameV(self, stones):\n """\n :type stoneValue: List[int]\n :rtype: int\n """\n n = le
|
ysz951
|
NORMAL
|
2020-08-23T04:19:11.844616+00:00
|
2020-08-23T04:19:11.844650+00:00
| 96 | false |
```\nclass Solution(object):\n def stoneGameV(self, stones):\n """\n :type stoneValue: List[int]\n :rtype: int\n """\n n = len(stones)\n preSum = [0] * (n + 1)\n for i in range(1, n + 1):\n preSum[i] = stones[i - 1] + preSum[i - 1]\n memo = {}\n def dfs(s, e):\n if s == e: return 0\n if (s, e) in memo: return memo[(s, e)]\n res = -float(\'inf\')\n for i in range(s, e):\n option1 = preSum[i + 1] - preSum[s]\n option2 = preSum[e + 1] - preSum[i + 1]\n if option1 > option2:\n res = max(res, option2 + dfs(i + 1, e))\n elif option1 < option2:\n res = max(res, option1 + dfs(s, i))\n else:\n res = max(res, option1 + dfs(s, i), option2 + dfs(i + 1, e))\n memo[(s, e)] = res\n return res\n return dfs(0, n - 1)\n```
| 1 | 0 |
[]
| 0 |
stone-game-v
|
[Java] 45ms clean code, Top down dp O(n^3)
|
java-45ms-clean-code-top-down-dp-on3-by-6kuj3
|
Java\nclass Solution {\n public int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length;\n int[] preSum = new int[n + 1];\n for (
|
binglelove
|
NORMAL
|
2020-08-23T04:11:47.131280+00:00
|
2020-08-23T04:11:47.131337+00:00
| 129 | false |
```Java\nclass Solution {\n public int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length;\n int[] preSum = new int[n + 1];\n for (int i = 0; i < n; i++)\n preSum[i + 1] = preSum[i] + stoneValue[i];\n int[][] memo = new int[n][n];\n return dfs(stoneValue, preSum, 0, n - 1, memo);\n }\n \n private int dfs(int[] stone, int[] preSum, int left, int right, int[][] memo) {\n if (left >= right) return 0;\n if (left + 1 == right) return Math.min(stone[left], stone[right]);\n if (memo[left][right] != 0) return memo[left][right];\n \n int res = 0;\n for (int i = left; i <= right; i++) {\n int leftSum = preSum[i + 1] - preSum[left];\n int rightSum = preSum[right + 1] - preSum[i + 1];\n \n if (leftSum >= rightSum) res = Math.max(res, rightSum + dfs(stone, preSum, i + 1, right, memo));\n if (leftSum <= rightSum) res = Math.max(res, leftSum + dfs(stone, preSum, left, i, memo));\n }\n memo[left][right] = res;\n return res;\n }\n}\n```
| 1 | 1 |
[]
| 0 |
stone-game-v
|
Any idea how to speedup bottoms up DP ? | C++ | O(N^3) | TLE
|
any-idea-how-to-speedup-bottoms-up-dp-c-alf80
|
imo, dp questions should accept both top down and bottom up approaches. No able to figure out what I could have done to improve this solution. Suggestions are w
|
all_might
|
NORMAL
|
2020-08-23T04:05:42.285150+00:00
|
2020-08-23T04:11:08.659923+00:00
| 156 | false |
> imo, dp questions should accept both top down and bottom up approaches. No able to figure out what I could have done to improve this solution. Suggestions are welcome.\n\n```\nclass Solution {\npublic:\n typedef long long ll;\n int stoneGameV(vector<int>& sv) {\n int n = sv.size();\n vector<int> presum(n, 0);\n for (int i = 0; i<n; i++) presum[i] = sv[i] + ((i>0)?presum[i-1]:0);\n\n vector<vector<ll>> dp(n, vector<ll>(n, INT_MIN));\n\n for (int l = 0; l<n; l++) {\n for (int i = 0; i<(n-l); i++){ \n int j = i+l;\n if (i==j) dp[i][j] = 0;\n else if(i+1 == j) dp[i][j] = min(sv[i], sv[j]);\n else {\n ll &v = dp[i][j];\n for (int k = i+1; k<=j; k++) {\n int lsum = presum[k-1] - ((i>0)?presum[i-1]:0);\n int rsum = presum[j] - presum[k-1];\n\n if (rsum == lsum) v = max(dp[i][k-1],dp[k][j]) + lsum;\n else if (lsum > rsum) v = max(v, rsum + dp[k][j]);\n else v = max(v, lsum + dp[i][k-1]);\n }\n }\n }\n }\n\n return dp[0][n-1];\n }\n};\n```
| 1 | 0 |
[]
| 2 |
stone-game-v
|
C++ DP | Easy Solution | Memoization
|
c-dp-easy-solution-memoization-by-kaintp-ydam
|
class Solution {\npublic:\n \n \n int findMax(vector&prefix, int start, int end, vector>&dp ){\n \n if(start==end){\n return 0
|
kaint
|
NORMAL
|
2020-08-23T04:05:40.851553+00:00
|
2020-08-23T04:09:10.862069+00:00
| 95 | false |
class Solution {\npublic:\n \n \n int findMax(vector<int>&prefix, int start, int end, vector<vector<int>>&dp ){\n \n if(start==end){\n return 0;\n } \n if(dp[start][end]!=-1)\n return dp[start][end];\n int maxans=0;\n \n for(int cut=start;cut<end;cut++){\n \n int leftRowSum=prefix[cut]-prefix[start-1];\n int rightRowSum=prefix[end]-prefix[cut];\n \n if(leftRowSum < rightRowSum ){\n maxans=max(maxans, leftRowSum+findMax(prefix, start, cut,dp));\n }else if(leftRowSum>rightRowSum){\n maxans=max(maxans, rightRowSum+findMax(prefix, cut+1, end,dp));\n }else{\n maxans=max(maxans, leftRowSum+findMax(prefix, start, cut, dp));\n maxans=max(maxans, rightRowSum+findMax(prefix, cut+1, end, dp));\n }\n }\n \n return dp[start][end]=maxans;\n }\n\n int stoneGameV(vector<int>& arr) {\n \n arr.insert(arr.begin(),0);\n vector<vector<int>>dp(502,vector<int>(502,-1));\n \n for(int i=2;i<arr.size();i++){\n arr[i]+=arr[i-1];\n } \n\t\t\n return findMax(arr, 1, arr.size()-1,dp);\n }\n};
| 1 | 0 |
[]
| 0 |
stone-game-v
|
[Java] Top Down DP with Memo O(N^3)
|
java-top-down-dp-with-memo-on3-by-yuhwu-vg24
|
\nclass Solution {\n int[][] memo;\n public int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length;\n int[] pSum = new int[n+1];\n
|
yuhwu
|
NORMAL
|
2020-08-23T04:02:17.321815+00:00
|
2020-08-23T04:02:17.321877+00:00
| 119 | false |
```\nclass Solution {\n int[][] memo;\n public int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length;\n int[] pSum = new int[n+1];\n memo = new int[n+1][n+1];\n for(int i=1; i<=n; i++){\n pSum[i] = pSum[i-1] + stoneValue[i-1];\n }\n return calc(pSum, 0, n-1);\n }\n \n public int calc(int[] pSum, int lo, int hi){\n if(lo>=hi){\n return 0;\n }\n if(memo[lo][hi]!=0){\n return memo[lo][hi];\n }\n int max = 0;\n for(int k=lo; k<hi; k++){\n int cur = 0;\n int left = pSum[k+1] - pSum[lo];\n int right = pSum[hi+1] - pSum[k+1];\n if(left>right){\n cur = right + calc(pSum, k+1, hi);\n }\n else if(left<right){\n cur = left + calc(pSum, lo, k);\n }\n else{\n cur = left + Math.max(calc(pSum, lo, k), calc(pSum, k+1, hi));\n }\n max = Math.max(max, cur);\n }\n memo[lo][hi] = max;\n return max;\n }\n}\n```
| 1 | 0 |
[]
| 0 |
stone-game-v
|
Easy To understand! JAVA DFS+Memory+preSum!!
|
easy-to-understand-java-dfsmemorypresum-8u3vh
|
I think it is clear to understand! Maybe someone can help me to explain it.\n\n\nclass Solution {\n public int stoneGameV(int[] stoneValue) {\n\n int
|
sugersu
|
NORMAL
|
2020-08-23T04:02:13.159504+00:00
|
2020-08-23T04:02:13.159572+00:00
| 112 | false |
I think it is clear to understand! Maybe someone can help me to explain it.\n\n```\nclass Solution {\n public int stoneGameV(int[] stoneValue) {\n\n int n=stoneValue.length;\n if(n<2) return 0;\n \n long[] preSum=new long[n+1];\n Map<Pair<Integer,Integer>,Long> memo= new HashMap<>();\n for(int i=1;i<=n;i++){\n preSum[i]=preSum[i-1]+stoneValue[i-1];\n }\n \n return (int)dfs(preSum,0,n,memo);\n \n }\n\n long dfs(long[] sum, int lo, int hi, Map<Pair<Integer,Integer>,Long> memo){\n //System.out.println(lo+","+hi);\n if(lo+1==hi) return 0;\n Pair<Integer,Integer> key = new Pair<>(lo,hi);\n \n if(memo.containsKey(key)) return memo.get(key);\n \n long ans=0;\n for(int i=lo+1;i<hi;i++){\n long left=sum[i]-sum[lo];\n long right=sum[hi]-sum[i];\n \n if(left>right){\n ans=Math.max(right+dfs(sum,i,hi,memo),ans);\n }else if(left < right){\n ans=Math.max(left+dfs(sum,lo,i,memo),ans);\n }else{\n ans=Math.max(left+Math.max(dfs(sum,i,hi,memo),dfs(sum,lo,i,memo)),ans);\n }\n }\n \n memo.put(key,ans);\n return ans;\n }\n}\n```
| 1 | 0 |
[]
| 0 |
stone-game-v
|
Top Down DP with Memoization
|
top-down-dp-with-memoization-by-zsshen-rh2l
|
\nclass Solution {\npublic:\n int stoneGameV(vector<int>& arr) {\n \n int n = arr.size();\n\n vector<int> prefix(n + 1, 0);\n for
|
zsshen
|
NORMAL
|
2020-08-23T04:02:02.827965+00:00
|
2020-08-23T04:02:02.828013+00:00
| 123 | false |
```\nclass Solution {\npublic:\n int stoneGameV(vector<int>& arr) {\n \n int n = arr.size();\n\n vector<int> prefix(n + 1, 0);\n for (int i = 1 ; i <= n ; ++i) {\n prefix[i] = prefix[i - 1] + arr[i - 1];\n }\n \n vector<vector<int>> dp(n, vector<int>(n, -1));\n return topDown(arr, 0, n - 1, prefix, dp);\n }\n \nprivate:\n int topDown(\n vector<int>& arr,\n int l, int r,\n vector<int>& prefix,\n vector<vector<int>>& dp) {\n \n if (l == r) {\n return 0;\n }\n \n if (dp[l][r] != -1) {\n return dp[l][r];\n }\n \n int opt = 0; \n for (int m = l ; m < r ; ++m) {\n int left = prefix[m + 1] - prefix[l];\n int right = prefix[r + 1] - prefix[m + 1];\n \n if (left > right) {\n int sum = right + topDown(arr, m + 1, r, prefix, dp);\n opt = max(opt, sum);\n } else if (left < right) {\n int sum = left + topDown(arr, l, m, prefix, dp);\n opt = max(opt, sum);\n } else {\n int sum = right + topDown(arr, m + 1, r, prefix, dp);\n opt = max(opt, sum);\n sum = left + topDown(arr, l, m, prefix, dp);\n opt = max(opt, sum); \n }\n }\n \n return dp[l][r] = opt;\n }\n};\n```
| 1 | 0 |
[]
| 0 |
stone-game-v
|
[Python3] intuitive DP
|
python3-intuitive-dp-by-xavier90-g0oq
|
\nclass Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n n = len(stoneValue)\n \n pre = [0]\n for e in stoneValue:\n
|
xavier90
|
NORMAL
|
2020-08-23T04:01:33.439148+00:00
|
2020-08-27T23:54:09.155057+00:00
| 172 | false |
```\nclass Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n n = len(stoneValue)\n \n pre = [0]\n for e in stoneValue:\n pre.append(pre[-1]+e)\n \n import functools\n @functools.lru_cache(None)\n def dp(i, j):\n if i >= j:\n return 0\n res = 0\n for mid in range(i, j):\n\t\t\t\tleft = pre[mid+1]-pre[i]\n\t\t\t\tright = pre[j+1]-pre[mid+1]\n if right < left:\n res = max(res, dp(mid+1,j)+right)\n elif right > left:\n res = max(res, dp(i, mid)+left)\n else:\n res = max(res, dp(i, mid)+left, dp(mid+1,j)+right)\n return res\n return dp(0,n-1)\n```
| 1 | 1 |
[]
| 0 |
stone-game-v
|
[Java] Simple top-down dfs+memo(with comments)
|
java-simple-top-down-dfsmemowith-comment-0rki
|
Intuition\nSimulate the game by dividing the array into two subarrays at each iteration. Add the subarray with smaller sum to result of current search and conti
|
dorayaki1018
|
NORMAL
|
2020-08-23T04:01:30.858769+00:00
|
2020-08-23T04:22:01.977688+00:00
| 161 | false |
**Intuition**\nSimulate the game by dividing the array into two subarrays at each iteration. Add the subarray with smaller sum to result of current search and continue searching the subarray with smaller sum.\n\n`dp[i][j]` represents the max score we can get in range `[i, j]`\n\nWe use the `presum` array to comput the subarray sum in `O(1)`\n\n```java\nclass Solution {\n public int stoneGameV(int[] stoneValue) {\n int n = stoneValue.length, sum = 0;;\n Integer[][] dp = new Integer[n][n];\n // initialize presum array\n int[] presum = new int[n];\n for(int i = 0; i < n; i++) {\n sum += stoneValue[i];\n presum[i] = sum;\n }\n return dfs(dp, 0, n-1, presum, stoneValue);\n }\n \n private int dfs(Integer[][] dp, int start, int end, int[] presum, int[] stoneValue) {\n // base condition\n // when start == end, we already added the value in previous function all. \n if(start == end) {\n return 0;\n }\n // return if we already searched this range\n if(dp[start][end] != null) return dp[start][end];\n int res = 0;\n \n // left: [start, i]\n // right: (i, end]\n for(int i = start; i < end; i++) {\n int left = presum[i] - (start > 0 ? presum[start - 1] : 0);\n int right = presum[end] - presum[i];\n // add the smaller pile to current result and continue search on the smaller pile\n if(left > right) {\n res = Math.max(res, right + dfs(dp, i + 1, end, presum, stoneValue));\n } else if(left < right) {\n res = Math.max(res, left + dfs(dp, start, i, presum, stoneValue));\n } else {\n res = Math.max(res, right + dfs(dp, i + 1, end, presum, stoneValue));\n res = Math.max(res, left + dfs(dp, start, i, presum, stoneValue));\n }\n }\n return dp[start][end] = res;\n }\n}\n```\n\nTime: O(n<sup>3</sup>)\n\nSpace: O(n<sup>2</sup>)\n
| 1 | 0 |
[]
| 0 |
stone-game-v
|
[C++] Prefix Sum + DP (Memoization)
|
c-prefix-sum-dp-memoization-by-jayesh_jo-70tw
|
Complexity
Time complexity: O(n³)
Space complexity: O(n²)
Code
|
Jayesh_Joshi
|
NORMAL
|
2025-04-05T13:17:14.353885+00:00
|
2025-04-05T13:17:14.353885+00:00
| 1 | false |
# Complexity
- Time complexity: O(n³)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n²)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int n;
vector<int> v, p;
vector<vector<int>> dp;
int solve(int l, int r) {
if (l >= r)
return 0;
int ans = 0;
if (dp[l][r] != -1) {
return dp[l][r];
}
for (int k = l; k <= r; k++) {
int left = p[k];
if (l != 0) {
left -= p[l - 1];
}
int right = p[r] - p[k];
int cnt = 0;
if (left > right) {
cnt = right + solve(k + 1, r);
} else if (right > left) {
cnt = left + solve(l, k);
} else {
cnt = left + max(solve(l, k), solve(k + 1, r));
}
ans = max(ans, cnt);
}
return dp[l][r] = ans;
}
int stoneGameV(vector<int>& stoneValue) {
v = stoneValue;
n = v.size();
p.assign(n, 0);
p[0] = v[0];
for (int i = 1; i < n; i++) {
p[i] = p[i - 1] + v[i];
}
dp.assign(n + 1, vector<int>(n + 1, -1));
return solve(0, n - 1);
}
};
```
| 0 | 0 |
['C++']
| 0 |
stone-game-v
|
Simple|| DP || Memoization Code ||
|
simple-dp-memoization-code-by-rwt2003-gida
|
IntuitionApproachComplexity
Time complexity:
O(n^3)
Space complexity:
O(n^2)Code
|
rwt2003
|
NORMAL
|
2025-03-08T10:29:05.915101+00:00
|
2025-03-08T10:29:05.915101+00:00
| 2 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n^3)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n^2)
# Code
```cpp []
class Solution {
public:
int n;
int dp[505][505];
int rec(int i,int j,vector<int> &p){
//base case
if(i >= j)return 0;
//here we have to divide the v[i,....j];
if(dp[i][j] != -1)return dp[i][j];
int mx = INT_MIN;
for(int k = i;k<j;k++){
int leftSum = (i != 0) ? p[k] - p[i-1] : p[k];
int rightSum = p[j] - p[k];
if(rightSum > leftSum){
mx = max(mx,rec(i,k,p) + leftSum);
}else if(leftSum > rightSum){
mx = max(mx,rec(k+1,j,p) + rightSum);
}else{
mx = max(mx,rec(i,k,p) + leftSum);
mx = max(mx,rec(k+1,j,p) + rightSum);
}
}
return dp[i][j] = mx;
}
int stoneGameV(vector<int>& v) {
n = v.size();
memset(dp,-1,sizeof(dp));
vector<int> preSum(n,0);
preSum[0] = v[0];
for(int i=1;i<n;i++){
preSum[i] = preSum[i-1] + v[i];
}
return rec(0,n-1,preSum);
}
};
```
| 0 | 0 |
['C++']
| 0 |
stone-game-v
|
Easy CPP Solution
|
easy-cpp-solution-by-vidhyarthisunav-ors4
|
Code
|
vidhyarthisunav
|
NORMAL
|
2025-03-04T17:56:15.791401+00:00
|
2025-03-04T17:56:15.791401+00:00
| 5 | false |
# Code
```cpp []
class Solution {
public:
vector<int> prefix_sum;
int dp[501][501];
int dfs(int i, int j) {
if (i == j) return 0;
if (dp[i][j] != -1) return dp[i][j];
int res = 0;
for (int idx = i; idx < j; idx++) {
int left_sum = prefix_sum[idx + 1] - prefix_sum[i];
int right_sum = prefix_sum[j + 1] - prefix_sum[idx + 1];
if (left_sum < right_sum) {
res = max(res, left_sum + dfs(i, idx));
} else if (left_sum > right_sum) {
res = max(res, right_sum + dfs(idx + 1, j));
} else {
res = max(res, max(left_sum + dfs(i, idx), right_sum + dfs(idx + 1, j)));
}
}
return dp[i][j] = res;
}
int stoneGameV(vector<int>& stoneValue) {
int n = stoneValue.size();
prefix_sum.resize(n + 1, 0);
memset(dp, -1, sizeof(dp));
for (int i = 0; i < n; i++) {
prefix_sum[i + 1] = prefix_sum[i] + stoneValue[i];
}
return dfs(0, n - 1);
}
};
```
| 0 | 0 |
['C++']
| 0 |
stone-game-v
|
✅ C++ sol. using TOP DOWN (RECURSIVE) 2-d DP and PREFIX-SUM
|
c-sol-using-top-down-recursive-2-d-dp-an-vf43
|
Code
|
deepanshugupta134
|
NORMAL
|
2025-02-19T18:48:13.557923+00:00
|
2025-02-19T18:48:13.557923+00:00
| 6 | false |
# Code
```cpp []
class Solution {
public:
int dp[501][501];
int fun(vector<int>&v , vector<int>&ps , int l , int r ){
if(r - l == 0){
return 0 ;
}
if(dp[l][r] != -1){
return dp[l][r];
}
int ans = 0 ;
int lp = 0 , rp = 0 ;
for(int i=l ; i<r ; i++){
lp = ps[i] - ((l==0)? 0 : ps[l-1]);
rp = ps[r] - ps[i] ;
if(rp == lp){
ans = max(lp + fun(v , ps , l , i) , rp + fun(v , ps , i+1 , r ));
}
else if(lp > rp){
ans = max(ans , rp + fun(v , ps , i+1 , r ));
}
else{
ans = max(ans , lp + fun(v , ps , l , i));
}
}
return dp[l][r] = ans ;
}
int stoneGameV(vector<int>& stoneValue) {
memset(dp , -1 , sizeof(dp));
int n = stoneValue.size();
vector<int>v(n);
v[0] = stoneValue[0];
for(int i=1 ; i<n ; i++){
v[i] = v[i-1] + stoneValue[i];
}
return fun(stoneValue , v , 0 , n-1 );
}
};
```
| 0 | 0 |
['Array', 'Dynamic Programming', 'Recursion', 'Memoization', 'Game Theory', 'C++']
| 0 |
stone-game-v
|
Bottom up DP with Knuth optimization
|
bottom-up-dp-with-knuth-optimization-by-hflwb
|
ApproachBottom up DP with Knuth optimization.Sorry in Japanese, but refer tomy blog postfor the idea.Complexity
Time complexity:O(N^2)
Space complexity:O(N^2)
|
kudojp
|
NORMAL
|
2025-02-18T09:27:28.795886+00:00
|
2025-02-18T09:29:18.085076+00:00
| 6 | false |
# Approach
Bottom up DP with Knuth optimization.
Sorry in Japanese, but refer to [my blog post](https://qiita.com/kudojp/items/5811b6d6444c866780a5) for the idea.
# Complexity
- Time complexity: `O(N^2)`
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: `O(N^2)`
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def stoneGameV(self, stones: List[int]) -> int:
n = len(stones)
self.stones = stones
self.prefix_sum = self.build_prefix_sum(stones)
dp = [[None] * n for _ in range(n)]
best_cut = [[None] * n for _ in range(n)]
for i in range(n):
dp[i][i] = 0
best_cut[i][i] = i # I am not sure if this is really okay.
for right in range(1, n):
left = 0
# fill in cells in this order:
# (r, c) -> (r+1, c+1) -> (r+2, c+2) -> ...
while 0 <= left <= n-1 and 0 <= right <= n-1:
max_score = - math.inf
mid_then = None # In case of tie, any of mid is fine?
# knuth optimization
for mid in range(best_cut[left][right-1] - 1, best_cut[left+1][right] + 1 + 1):
if not left <= mid <= right - 1: continue
left_sum = self.value_sum(left, mid)
right_sum = self.value_sum(mid+1, right)
if left_sum == right_sum:
score = max(dp[left][mid] + left_sum, dp[mid+1][right] + right_sum)
elif left_sum < right_sum:
score = dp[left][mid] + left_sum
else:
score = dp[mid+1][right] + right_sum
if max_score < score:
max_score = score
mid_then = mid
dp[left][right] = max_score
best_cut[left][right] = mid_then
left += 1
right += 1
return dp[0][n-1]
def build_prefix_sum(self, arr):
curr_sum = 0
ret = []
for num in arr:
curr_sum += num
ret.append(curr_sum)
return ret
@cache
def value_sum(self, left, right):
if left == 0:
return self.prefix_sum[right]
return self.prefix_sum[right] - self.prefix_sum[left - 1]
```
| 0 | 0 |
['Python3']
| 0 |
stone-game-v
|
Solution using Prefix sum and DP
|
solution-using-prefix-sum-and-dp-by-user-47qv
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
user5947v
|
NORMAL
|
2025-01-30T09:03:49.144909+00:00
|
2025-01-30T09:03:49.144909+00:00
| 2 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
int _stoneGameV(vector<int>& stoneValue, vector<vector<int>>& dp, vector<int>& prefSum, int l, int r) {
if(l==r) {
return dp[l][r] = 0;
}
if(dp[l][r]!=-1) return dp[l][r];
int max_ans = 0;
for(int i=l+1;i<r;i++) {
int leftSum = prefSum[i]-prefSum[l];
int rightSum = prefSum[r] - prefSum[i];
int ans = 0;
if(leftSum < rightSum)
ans = _stoneGameV(stoneValue, dp, prefSum, l, i) + leftSum;
else if(leftSum > rightSum)
ans = _stoneGameV(stoneValue, dp, prefSum, i, r) + rightSum;
else {
ans = max(_stoneGameV(stoneValue, dp, prefSum, l, i)+leftSum, _stoneGameV(stoneValue, dp, prefSum, i, r)+rightSum);
}
max_ans = max(max_ans, ans);
}
return dp[l][r] = max_ans;
}
public:
int stoneGameV(vector<int>& stoneValue) {
int n = stoneValue.size();
vector<vector<int>> dp(n+1, vector<int>(n+1, -1));
vector<int> prefSum(n+1, 0);
for(int i=1;i<=n;i++) {
prefSum[i] = (i==0 ? 0 : prefSum[i-1]) + stoneValue[i-1];
}
return _stoneGameV(stoneValue, dp, prefSum, 0, n);
}
};
```
| 0 | 0 |
['C++']
| 0 |
stone-game-v
|
1563. Stone Game V
|
1563-stone-game-v-by-g8xd0qpqty-ii15
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
G8xd0QPqTy
|
NORMAL
|
2025-01-13T16:24:20.719004+00:00
|
2025-01-13T16:24:20.719004+00:00
| 4 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int stoneGameV(vector<int>& stoneValue) {
int n = stoneValue.size();
vector<int> prefixSum(n + 1, 0);
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = 1; i <= n; ++i) {
prefixSum[i] = prefixSum[i - 1] + stoneValue[i - 1];
}
for (int len = 2; len <= n; ++len) {
for (int left = 0; left + len - 1 < n; ++left) {
int right = left + len - 1;
for (int mid = left; mid < right; ++mid) {
int leftSum = prefixSum[mid + 1] - prefixSum[left];
int rightSum = prefixSum[right + 1] - prefixSum[mid + 1];
if (leftSum > rightSum) {
dp[left][right] = max(dp[left][right], rightSum + dp[mid + 1][right]);
} else if (rightSum > leftSum) {
dp[left][right] = max(dp[left][right], leftSum + dp[left][mid]);
} else {
dp[left][right] = max(dp[left][right], max(leftSum + dp[left][mid], rightSum + dp[mid + 1][right]));
}
}
}
}
return dp[0][n - 1];
}
};
```
| 0 | 0 |
['C++']
| 0 |
stone-game-v
|
Why this problem pass all cases in cpp but not in python3.
|
why-this-problem-pass-all-cases-in-cpp-b-ixei
|
Code
|
bepriyansh
|
NORMAL
|
2025-01-02T13:24:42.378145+00:00
|
2025-01-02T13:24:42.378145+00:00
| 4 | false |
# Code
```cpp []
class Solution {
vector<int> sv, pre;
vector<vector<int>> cache;
int n;
int gs(int l, int r) { return pre[r] - (l > 0 ? pre[l - 1] : 0); }
int dp(int l, int r) {
if (l == r)
return 0;
if (cache[l][r] != -1)
return cache[l][r];
int res = 0;
for (int i = l + 1; i <= r; i++) {
int ls = gs(l, i - 1), rs = gs(i, r);
if (ls <= rs) {
res = max(res, ls + dp(l, i - 1));
}
if (ls >= rs) {
res = max(res, rs + dp(i, r));
}
}
return cache[l][r] = res;
}
public:
int stoneGameV(vector<int>& _sv) {
this->sv = _sv;
n = size(sv);
pre.resize(n, 0);
cache = vector<vector<int>>(n+1, vector<int>(n+1, -1));
pre[0] = sv[0];
for (int i = 1; i < n; i++) {
pre[i] = pre[i - 1] + sv[i];
}
return dp(0, n - 1);
}
};
```
```python3 []
class Solution:
def stoneGameV(self, sv: List[int]) -> int:
n = len(sv)
pre = [0] * n
pre[0] = sv[0]
for i in range(1, n):
pre[i] = sv[i] + pre[i - 1]
def gs(l, r):
return pre[r] - (pre[l - 1] if l > 0 else 0)
@cache
def dp(l, r):
if l == r:
return 0
res = 0
for i in range(l + 1, r + 1):
ls, rs = gs(l, i - 1), gs(i, r)
if ls <= rs:
res = max(res, ls + dp(l, i - 1))
if ls >= rs:
res = max(res, rs + dp(i, r))
return res
return dp(0, n - 1)
```
| 0 | 0 |
['C++']
| 0 |
stone-game-v
|
Dynamic Programming with Prefix Sum - O(N^3) - C++
|
dynamic-programming-with-prefix-sum-on3-et2p5
|
Intuition The problem is about maximizing a score obtained by choosing optimal subarrays in a sequence. The recursive nature of evaluating subarrays makes it co
|
upperknoot
|
NORMAL
|
2024-11-19T22:12:05.903644+00:00
|
2024-11-19T22:12:05.903679+00:00
| 6 | false |
# Intuition
The problem is about maximizing a score obtained by choosing optimal subarrays in a sequence. The recursive nature of evaluating subarrays makes it conducive to a dynamic programming approach. We can utilize prefix sums to efficiently compute the sum of any subarray, which is a key operation in the solution.
# Approach
The approach involves using dynamic programming to solve subproblems of choosing the best scoring strategy for subarrays. We use prefix sums to quickly calculate subarray sums and a memoization table to store results of subproblems to avoid redundant calculations.
1. **Initialize Prefix Sum Array**:
- We create a prefix sum array to store cumulative sums of the stone values. This allows us to compute the sum of any subarray in constant time by subtracting two prefix sums.
2. **Define Recursive Function with Memoization**:
- We define a recursive function `solve(i, j)` that returns the maximum score obtainable from the subarray starting at index $i$ and ending at index $j$. The function uses a memoization table `dp` to store results of previously computed subproblems.
3. **Iterate Over Possible Partitions**:
- For each subarray defined by indices $i$ and $j$, we iterate over possible partition points $k$. For each partition, we compute the sum of the left and right subarrays using the prefix sum array.
4. **Calculate Maximum Score**:
- Depending on the sums of the left and right subarrays, we recursively compute the scores for the remaining subarrays and determine the maximum score possible. If the sums are equal, we consider both possible partitions.
5. **Store and Return Result**:
- The result for each subarray is stored in the `dp` table, and the function returns the result, ensuring subproblems are solved only once.
# Complexity
- Time complexity:
O(n^3)
- The outer function `stoneGameV` initializes a prefix sum array and calls `solve(0, n-1)`, which is $O(n)$ for initialization.
- The recursive function `solve(i, j)` iterates over $k$ from $i$ to $j-1$, leading to $O(n)$ iterations.
- For each $k$, we perform constant time operations and recursive calls, leading to a total of $O(n^2)$ recursive subproblems.
- Each subproblem involves iterating up to $n$ times, resulting in $O(n^3)$ overall complexity.
- Memory complexity:
O(n^2)
- The space complexity is dominated by the `dp` table, which stores the results for each subarray $(i, j)$. This requires $O(n^2)$ space.
- The prefix sum array uses $O(n)$ space, but this is overshadowed by the $dp$ table size.
# Code
```cpp
class Solution {
public:
int stoneGameV(vector<int>& stoneValue) {
int n = stoneValue.size();
vector<vector<int>> dp(n, vector<int>(n, -1));
vector<int> prefix(n + 1, 0);
for (int i = 0; i < n; i++) {
prefix[i + 1] = prefix[i] + stoneValue[i];
}
return solve(0, n - 1, stoneValue, prefix, dp);
}
int solve(int i, int j, vector<int>& stoneValue, vector<int>& prefix, vector<vector<int>>& dp) {
if (i == j) return 0;
if (dp[i][j] != -1) return dp[i][j];
int res = 0;
for (int k = i; k < j; k++) {
int left = prefix[k + 1] - prefix[i];
int right = prefix[j + 1] - prefix[k + 1];
if (left > right) {
// discard left side
res = max(res, right + solve(k + 1, j, stoneValue, prefix, dp));
} else if (left < right) {
// discard right side
res = max(res, left + solve(i, k, stoneValue, prefix, dp));
} else {
// let alice choose the better side
res = max(
left + solve(i, k, stoneValue, prefix, dp),
right + solve(k + 1, j, stoneValue, prefix, dp)
);
}
}
return dp[i][j] = res;
}
};
```
| 0 | 0 |
['Dynamic Programming', 'Prefix Sum', 'C++']
| 0 |
stone-game-v
|
Swift with recursion + caching.
|
swift-with-recursion-caching-by-wenjiema-iiwo
|
Intuition\nThe problem can be solved with recursion. Two helper functions each represent Alice and Bob, they both return Alice\'s sum:\n1. Alice would devide ar
|
wenjiema
|
NORMAL
|
2024-11-08T20:58:41.073531+00:00
|
2024-11-08T20:58:41.073552+00:00
| 1 | false |
# Intuition\nThe problem can be solved with recursion. Two helper functions each represent Alice and Bob, they both return Alice\'s sum:\n1. Alice would devide array into two parts, and find the division that returns biggest result.\n2. Bob would throw away array with the bigger sum, then add the smaller sum to Alice\'s sum and give back alice the array; When their sum equal, Bob will let alice decide which one to pick (the larger result). \n\nOnce the recursion solution is in place, caching can be added easily to bring down time complexity to O(n^2) \n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```swift []\nclass Solution {\n var sumVal: [[Int]] = []\n\n func stoneGameV(_ stoneValue: [Int]) -> Int {\n sumVal = Array(repeating: Array(repeating: 0, count: stoneValue.count), count: stoneValue.count)\n for i in 0..<stoneValue.count {\n for j in i..<stoneValue.count {\n if i == j {\n sumVal[i][j] = stoneValue[i]\n } else {\n sumVal[i][j] = stoneValue[j] + sumVal[i][j-1]\n }\n }\n }\n\n var c = Array(repeating: Array(repeating: -1, count: stoneValue.count), count: stoneValue.count)\n\n return alice(stoneValue, 0, stoneValue.count-1, &c)\n }\n\n func alice(_ stoneValue: [Int], _ i: Int, _ j: Int, _ c: inout [[Int]]) -> Int {\n if i == j {\n return 0\n }\n\n if c[i][j] != -1 {\n return c[i][j]\n }\n\n var res = 0\n for k in i...j-1 {\n res = max(res, bob(stoneValue, i, k, j, &c))\n }\n c[i][j] = res\n return res\n }\n\n func bob(_ stoneValue: [Int], _ i: Int, _ j: Int, _ k: Int, _ c: inout [[Int]]) -> Int {\n let s1 = sumVal[i][j]\n let s2 = sumVal[j+1][k]\n\n if s1 > s2 {\n return alice(stoneValue, j+1, k, &c) + s2\n } else if s1 < s2 {\n return alice(stoneValue, i,j, &c) + s1\n } else {\n return max(alice(stoneValue, j+1, k, &c) + s2, alice(stoneValue, i,j, &c) + s1)\n }\n }\n}\n```
| 0 | 0 |
['Swift']
| 0 |
stone-game-v
|
My java 287ms solution 33% faster
|
my-java-287ms-solution-33-faster-by-ragh-ut4r
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
raghavrathore7415
|
NORMAL
|
2024-10-27T05:07:38.217977+00:00
|
2024-10-27T05:07:38.217999+00:00
| 3 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int stoneGameV(int[] stoneValue) {\n int[] psum = new int[stoneValue.length];\n psum[0] = stoneValue[0];\n for(int i = 1; i < psum.length; i++){\n psum[i] = stoneValue[i] + psum[i - 1];\n }\n return getMax(0, stoneValue.length - 1, stoneValue, psum, new Integer[psum.length][psum.length]);\n }\n // 1 2 3 4 5 6 7 8\n public int getMax(int low, int high, int[] arr, int[] psum, Integer[][] cache){\n if(low == high){\n return 0;\n }\n if(cache[low][high] != null){\n return cache[low][high];\n }\n int res = 0;\n for(int i = low; i < high; i++){\n int lsum = low > 0 ? psum[i] - psum[low - 1] : psum[i];\n int hsum = psum[high] - psum[i];\n if(lsum > hsum){\n res = Math.max(res, hsum + getMax(i + 1, high, arr, psum, cache));\n }else if(lsum < hsum){\n res = Math.max(res, lsum + getMax(low, i, arr, psum, cache));\n }else{\n res = Math.max(res, hsum + getMax(i + 1, high, arr, psum, cache));\n res = Math.max(res, lsum + getMax(low, i, arr, psum, cache));\n }\n }\n return cache[low][high] = res;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
stone-game-v
|
[Accepted] Swift
|
accepted-swift-by-vasilisiniak-9arq
|
\nclass Solution {\n func stoneGameV(_ stoneValue: [Int]) -> Int {\n\n let sum = stoneValue.reduce(into: [0]) { $0.append($0.last! + $1) }\n \n
|
vasilisiniak
|
NORMAL
|
2024-10-07T09:53:44.373752+00:00
|
2024-10-07T09:53:44.373785+00:00
| 0 | false |
```\nclass Solution {\n func stoneGameV(_ stoneValue: [Int]) -> Int {\n\n let sum = stoneValue.reduce(into: [0]) { $0.append($0.last! + $1) }\n \n var dp = Array(\n repeating: Array(repeating: 0, count: stoneValue.count),\n count: stoneValue.count\n )\n\n for r in 1..<stoneValue.count {\n for l in (0..<r).reversed() {\n \n for m in l..<r {\n let sl = sum[m + 1] - sum[l]\n let sr = sum[r + 1] - sum[m + 1]\n\n if sl <= sr {\n dp[l][r] = max(dp[l][r], sl + dp[l][m])\n }\n if sl >= sr {\n dp[l][r] = max(dp[l][r], sr + dp[m + 1][r])\n }\n }\n }\n }\n\n return dp[0][stoneValue.count - 1]\n }\n}\n```
| 0 | 0 |
['Swift']
| 0 |
stone-game-v
|
1563. Stone Game V.cpp
|
1563-stone-game-vcpp-by-202021ganesh-8x3l
|
Code\n\nclass Solution {\npublic:\n int stoneGameV(vector<int>& stoneValue) {\n int n = stoneValue.size();\n dp.resize(n, vector<int>(n, -1));\n retu
|
202021ganesh
|
NORMAL
|
2024-10-03T06:24:14.020888+00:00
|
2024-10-03T06:24:14.020923+00:00
| 5 | false |
**Code**\n```\nclass Solution {\npublic:\n int stoneGameV(vector<int>& stoneValue) {\n int n = stoneValue.size();\n dp.resize(n, vector<int>(n, -1));\n return stoneGameV(stoneValue, 0, n - 1);\n }\n private:\n vector<vector<int>> dp;\n int stoneGameV(const vector<int>& stoneValue, int i, int j) {\n if(i>j)\n return 0;\n if(dp[i][j]!=-1)\n return dp[i][j];\n int r=0;\n int l=0;\n for(int s=i;s<=j;s++){\n r+=stoneValue[s];\n }\n int ans=0;\n for (int p = i; p <j; ++p) {\n l+=stoneValue[p];\n r=r-stoneValue[p];\n if (l < r) \n ans = max(ans, l + stoneGameV(stoneValue, i, p));\n else if (l > r) \n ans = max(ans, r + stoneGameV(stoneValue, p+1, j));\n else if(l==r)\n ans = max(ans, l + max(stoneGameV(stoneValue, i, p), stoneGameV(stoneValue, p+1, j)));\n }\n return dp[i][j]=ans;\n }\n};\n```
| 0 | 0 |
['C']
| 0 |
stone-game-v
|
2D DP,WITH PREFIX SUM.
|
2d-dpwith-prefix-sum-by-damon109-ncwe
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is about maximizing Alice\'s score by carefully choosing how to split the a
|
damon109
|
NORMAL
|
2024-09-04T11:29:41.680759+00:00
|
2024-09-04T11:29:41.680787+00:00
| 6 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about maximizing Alice\'s score by carefully choosing how to split the array of stones in each round. Alice aims to divide the stones such that Bob is forced to throw away the row with the larger sum, leaving Alice with the row with the smaller sum, which becomes her score for that round. The challenge lies in finding the optimal way to split the array at each step to maximize Alice\'s total score across all rounds.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPrefix Sum Array:\n\nCreate a prefix sum array to quickly calculate the sum of any subarray. This will help in determining the sums of the left and right partitions during each split.\nDynamic Programming (DP):\n\nDefine a 2D DP table dp[i][j] where dp[i][j] represents the maximum score Alice can obtain from the subarray starting at index i and ending at index j.\nUse a bottom-up approach to fill this DP table. For each possible subarray, iterate through all possible split points to decide the optimal partition that maximizes Alice\'s score.\nBinary Search for Efficient Partitioning:\n\nFor each subarray, instead of checking all possible partitions, use binary search to find the point where the sum of the left partition is as close as possible to the sum of the right partition.\nState Transition:\n\nFor each split point, calculate the potential score for Alice based on whether Bob chooses the left or right partition to discard.\nUpdate dp[i][j] with the maximum score Alice can achieve for that subarray.\nFinal Result:\n\nThe final answer will be stored in dp[0][n-1], which represents the maximum score Alice can achieve starting from the entire array.\nThis approach ensures that Alice\'s score is maximized while also being computationally efficient.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int stoneGameV(vector<int>& sv) {\n int n = sv.size();\n vector<vector<int>> dp(n, vector<int>(n, 0));\n vector<int> prefixSum(n + 1, 0);\n\n // Calculate prefix sum\n for (int i = 0; i < n; ++i) {\n prefixSum[i + 1] = prefixSum[i] + sv[i];\n }\n\n // DP with binary search\n for (int len = 2; len <= n; ++len) {\n for (int i = 0; i + len <= n; ++i) {\n int j = i + len - 1;\n\n for (int k = i; k < j; ++k) {\n int leftSum = prefixSum[k + 1] - prefixSum[i];\n int rightSum = prefixSum[j + 1] - prefixSum[k + 1];\n\n if (leftSum < rightSum) {\n dp[i][j] = max(dp[i][j], dp[i][k] + leftSum);\n } else if (leftSum > rightSum) {\n dp[i][j] = max(dp[i][j], dp[k + 1][j] + rightSum);\n } else {\n dp[i][j] = max(dp[i][j], max(dp[i][k] + leftSum, dp[k + 1][j] + rightSum));\n }\n }\n }\n }\n\n return dp[0][n - 1];\n }\n};\n\n\n\n\n // int n=sv.size(), left=1,right=n,count=0;\n // vector<int> sum;\n // sum.push_back(0);\n // for(int i=0;i<n;i++){\n // sum[i+1]=sv[i]+sum[i];\n // }\n // while(left+1!=right){\n // int ind=*lower_bound(sum.begin(),sum.end(),sum[right]/2);\n // if((sum[right]+1)/2==sum[ind]){\n // //same left and right\n // }else{\n // if((sum[right]+1)/2-sum[ind-1]<sum[ind]-(sum[right]+1)/2){\n // ind=ind-1;\n // }\n \n // }\n // }\n```
| 0 | 0 |
['Dynamic Programming', 'C++']
| 0 |
stone-game-v
|
My Solution
|
my-solution-by-hope_ma-7uh5
|
\n/**\n * let `n` be the length of the vector `stoneValue`\n *\n * the dp solution is employed.\n * dp[start][end] stands for the maximum score that Alice can o
|
hope_ma
|
NORMAL
|
2024-09-03T06:33:38.858938+00:00
|
2024-09-03T16:16:02.803281+00:00
| 3 | false |
```\n/**\n * let `n` be the length of the vector `stoneValue`\n *\n * the dp solution is employed.\n * dp[start][end] stands for the maximum score that Alice can obtain from the sub-row whose range is from the index\n * `start` to the index `end` of the vector `stoneValue`, `start` inclusive, `end` exclusive\n *\n * initial:\n * dp[start][start + 1] = 0, where `start` is in the range [0, n - 1], both inclusive\n *\n * induction:\n * let `sum[i][j]` be the sum from stoneValue[i] to stoneValue[j], `i` inclusive, `j` exclusive\n * for every `start`, `end`, where `end` - `start` > 1,\n * let `separator` be an index such that\n * 1) sum[start][separator + 1] >= sum[separator + 1][end] and\n * 2) sum[start][separator] < sum[separator][end],\n * case 1:\n * if sum[start][separator + 1] == sum[separator + 1][end]\n * dp[start][end] = max(\n * sum[start][i] + dp[start][i] for every `i` in the range [start + 1, separator + 1], both inclusive,\n * sum[j][end] + dp[j][end] for every `j` in the range [separator + 1, end - 1], both inclusive\n * )\n * case 2:\n * if sum[start][separator + 1] > sum[separator + 1][end]\n * dp[start][end] = max(\n * sum[start][i] + dp[start][i] for every `i` in the range [start + 1, separator], both inclusive,\n * sum[j][end] + dp[j][end] for every `j` in the range [separator + 1, end - 1], both inclusive\n * )\n * let `left_max[i][j]` stands for\n * max(\n * sum[i][i + 1] + dp[i][i + 1],\n * sum[i][i + 2] + dp[i][i + 2],\n * ...\n * sum[i][j] + dp[i][j]\n * )\n * let `right_max[i][j]` stands for\n * max(\n * sum[j - 1][j] + dp[j - 1][j],\n * sum[j - 2][j] + dp[j - 2][j],\n * ...\n * sum[i][j] + dp[i][j]\n * )\n * `left_max[i][j]` and `right_max[i][j]` can be calculated by the following inductions,\n * left_max[i][j] = max(left_max[i][j - 1], sum[i][j] + dp[i][j])\n * right_max[i][j] = max(right_max[i + 1][j], sum[i][j] + dp[i][j])\n * then `case 1` and `case 2` can be reduced as following,\n * case 1:\n * dp[start][end] = max(left_max[start][separator + 1], right_max[separator + 1][end])\n * case 2:\n * dp[start][end] = max(left_max[start][separator], right_max[separator + 1][end])\n *\n * target:\n * dp[0][n]\n *\n * Time Complexity: O(n * n)\n * Space Complexity: O(n * n)\n */\nclass Solution {\n public:\n int stoneGameV(const vector<int> &stoneValue) {\n const int n = static_cast<int>(stoneValue.size());\n int presums[n + 1];\n memset(presums, 0, sizeof(presums));\n for (int i = 0; i < n; ++i) {\n presums[i + 1] = presums[i] + stoneValue[i];\n }\n\n int separators[n + 1][n + 1];\n memset(separators, 0, sizeof(separators));\n for (int start = 0; start < n; ++start) {\n for (int separator = start, end = start + 1; end < n + 1; ++end) {\n for (; presums[separator + 1] - presums[start] < presums[end] - presums[separator + 1]; ++separator) {\n }\n separators[start][end] = separator;\n }\n }\n \n int dp[n + 1][n + 1];\n memset(dp, 0, sizeof(dp));\n int left_max[n + 1][n + 1];\n memset(left_max, 0, sizeof(left_max));\n int right_max[n + 1][n + 1];\n memset(right_max, 0, sizeof(right_max));\n for (int length = 1; length < n + 1; ++length) {\n for (int start = 0; start + length - 1 < n; ++start) {\n const int end = start + length;\n const int separator = separators[start][end];\n const int left = presums[separator + 1] - presums[start];\n const int right = presums[end] - presums[separator + 1];\n if (left == right) {\n dp[start][end] = max(left_max[start][separator + 1], right_max[separator + 1][end]);\n } else {\n dp[start][end] = max(left_max[start][separator], right_max[separator + 1][end]);\n }\n \n left_max[start][end] = max(left_max[start][end - 1], presums[end] - presums[start] + dp[start][end]);\n right_max[start][end] = max(right_max[start + 1][end], presums[end] - presums[start] + dp[start][end]);\n }\n }\n return dp[0][n];\n }\n};\n```
| 0 | 0 |
[]
| 0 |
find-n-unique-integers-sum-up-to-zero
|
[Java/C++/Python] Find the Rule
|
javacpython-find-the-rule-by-lee215-1iuj
|
Intuition\nNaive idea\nn = 1, [0]\nn = 2, [-1, 1]\n\nNow write more based on this\nn = 3, [-2, 0, 2]\nn = 4, [-3, -1, 1, 3]\nn = 5, [-4, -2, 0, 2, 4]\n\nIt spre
|
lee215
|
NORMAL
|
2019-12-30T17:11:21.003630+00:00
|
2020-01-10T03:05:24.181938+00:00
| 38,328 | false |
## **Intuition**\nNaive idea\n`n = 1, [0]`\n`n = 2, [-1, 1]`\n\nNow write more based on this\n`n = 3, [-2, 0, 2]`\n`n = 4, [-3, -1, 1, 3]`\n`n = 5, [-4, -2, 0, 2, 4]`\n\nIt spreads like the wave.\n<br>\n\n## **Explanation**\nFind the rule\n`A[i] = i * 2 - n + 1`\n<br>\n\n## **Math Observation**\n@zzg_zzm helps explain in math.\n\nActually, this rule could be derived from constructing an arithmetic sequence.\n\n(Note that any arithmetic sequence must have unique values if the common delta is non-zero)\n\nWe need the sequence sum, so that\n\n`(a[0] + a[n-1]) * n / 2 = 0`, which means `a[0] + a[n-1] = 0`.\n\nNote that `a[n-1] - a[0] = (n-1) * delta`, which is `-2 * a[0]`,\n\nso we simply set `delta = 2, a[0] = 1 - n`\n<br>\n\n\n## **Note**\nIt\'s not bad to sum up `1 + 2 + 3 + ... + (N - 1)`.\nPersonally I don\'t really like it much.\nWhat is the possible problem of this approach?\nIt doesn\'t work if `N` goes up to `10^5`\n<br>\n\n## **Complexity**\nTime `O(N)`\nSpace `O(N)`\n<br>\n\n**Java:**\n```java\n public int[] sumZero(int n) {\n int[] A = new int[n];\n for (int i = 0; i < n; ++i)\n A[i] = i * 2 - n + 1;\n return A;\n }\n```\n\n**C++:**\n```cpp\n vector<int> sumZero(int n) {\n vector<int> A(n);\n for (int i = 0; i < n; ++i)\n A[i] = i * 2 - n + 1;\n return A;\n }\n```\n\n**Python:**\n```python\n def sumZero(self, n):\n return range(1 - n, n, 2)\n```\n
| 434 | 6 |
[]
| 61 |
find-n-unique-integers-sum-up-to-zero
|
Simple Java : Fill from both sides
|
simple-java-fill-from-both-sides-by-ansh-xr7n
|
start filling up from left and right complementary values (so if we insert 1 from left, insert -1 from right, then insert 2 from left and insert -2 from right a
|
anshu4intvcom
|
NORMAL
|
2019-12-29T04:14:58.290894+00:00
|
2019-12-29T04:14:58.291004+00:00
| 11,448 | false |
- start filling up from left and right complementary values (so if we insert 1 from left, insert -1 from right, then insert 2 from left and insert -2 from right and so on) :\n\n```\npublic int[] sumZero(int n) {\n int[] res = new int[n];\n int left = 0, right = n - 1, start = 1;\n while (left < right) {\n res[left++] = start;\n res[right--] = -start;\n start++;\n }\n return res;\n }\n```
| 153 | 5 |
[]
| 9 |
find-n-unique-integers-sum-up-to-zero
|
Keep it simple. Add all values till n-1 and then balance it with -sum.
|
keep-it-simple-add-all-values-till-n-1-a-02jl
|
Edited. As @StefanPochmann pointed out rightly. starting from i+1 instead of i to avoid the case of 0 and 0 when n = 2.\n```\nclass Solution {\n public int[]
|
Nayanava
|
NORMAL
|
2019-12-29T04:56:57.541423+00:00
|
2019-12-29T11:55:01.506084+00:00
| 7,223 | false |
Edited. As @StefanPochmann pointed out rightly. starting from i+1 instead of i to avoid the case of 0 and 0 when n = 2.\n```\nclass Solution {\n public int[] sumZero(int n) {\n int arr[] = new int[n];\n int sum = 0;\n for(int i = 0; i < n-1; i++) {\n arr[i] = i+1;\n sum += arr[i];\n }\n arr[n-1] = -sum;\n return arr;\n }\n}
| 70 | 6 |
[]
| 6 |
find-n-unique-integers-sum-up-to-zero
|
Trivial Python/Ruby/Java/C++
|
trivial-pythonrubyjavac-by-stefanpochman-wmz5
|
Just use the numbers 1, 2, ..., n-1 as well as their negated sum. I can\'t even be bothered to write the sum formula :-P\n\nPython\n\ndef sumZero(self, n):\n
|
stefanpochmann
|
NORMAL
|
2019-12-29T11:42:16.225447+00:00
|
2019-12-29T18:15:04.664368+00:00
| 4,809 | false |
Just use the numbers 1, 2, ..., n-1 as well as their negated sum. I can\'t even be bothered to write the sum formula :-P\n\n**Python**\n```\ndef sumZero(self, n):\n a = range(1, n)\n return a + [-sum(a)]\n```\n**Ruby**\nSlight variation since `2..n` is one character shorter than `1...n`.\n```\ndef sum_zero(n)\n a = 2..n\n a.to_a << -a.sum\nend\n```\n**Java**\n```\npublic int[] sumZero(int n) {\n int[] a = new int[n];\n for (int i = 1; i < n; i++) {\n a[i] = i;\n a[0] -= i;\n }\n return a;\n}\n```\nShorter but a bit less clear:\n```\npublic int[] sumZero(int n) {\n int[] a = new int[n];\n for (int i = 1; i < n; i++)\n a[0] -= a[i] += i;\n return a;\n}\n```\n**C++**\n```\nvector<int> sumZero(int n) {\n vector<int> a(n);\n for (int i = 1; i < n; i++) {\n a[i] = i;\n a[0] -= i;\n }\n return a;\n}\n```\nShorter but a bit less clear:\n```\nvector<int> sumZero(int n) {\n vector<int> a(n);\n for (int i = 1; i < n; i++)\n a[0] -= a[i] = i;\n return a;\n}\n```
| 55 | 6 |
[]
| 3 |
find-n-unique-integers-sum-up-to-zero
|
Java O(n) solution with explanation 0ms 100%
|
java-on-solution-with-explanation-0ms-10-sptv
|
Set the values at each sequential pair of indices such that they sum to 0 and each of these pairs is unique.\nIdea: use i,-i for the values at each pair of indi
|
eduardrg
|
NORMAL
|
2020-11-03T18:17:58.694643+00:00
|
2020-11-03T18:17:58.694688+00:00
| 3,421 | false |
Set the values at each sequential pair of indices such that they sum to 0 and each of these pairs is unique.\nIdea: use ```i,-i``` for the values at each pair of indices ```i, i+1```. \nThis won\'t work if ```i = 0``` because the first two elements would be ```0, 0```. Use ```i+1, -(i+1)``` instead to make it work for all ```i```.\nAfter the loop, all elements up to the last even index are unique and sum to ```0```. We don\'t have to worry if ```n``` is odd because the last element would have been initialized to ```0``` and ```0 + 0 = 0```, so we\'re done.\nStatements in the loop execute ```n/2``` times, so the time complexity is ```O(n)```.\n\n```\nclass Solution {\n public int[] sumZero(int n) {\n int[] result = new int[n];\n for (int i = 0; i < n - 1; i += 2) {\n result[i] = i + 1;\n result[i + 1] = -(i + 1);\n }\n return result;\n }\n}\n```
| 43 | 3 |
['Iterator', 'Java']
| 4 |
find-n-unique-integers-sum-up-to-zero
|
Python3 code: simple and readable with explanation
|
python3-code-simple-and-readable-with-ex-nvij
|
Explanation:\n# \nFirst, take a look at a few examples:\n\nn = 1: ans = [0]\nn = 2: ans = [-1,1]\nn = 3: ans = [-1,0,1]\nn = 4: ans = [-2,-1,1,2]\nn = 5: ans =
|
dr_sean
|
NORMAL
|
2020-01-04T22:03:36.359658+00:00
|
2020-01-05T04:13:06.361346+00:00
| 7,298 | false |
# Explanation:\n# \nFirst, take a look at a few examples:\n```\nn = 1: ans = [0]\nn = 2: ans = [-1,1]\nn = 3: ans = [-1,0,1]\nn = 4: ans = [-2,-1,1,2]\nn = 5: ans = [-2,-1,0,1,2]\n```\n\n- So, we should return an array where the values are symmetric. \n- If ```n%2``` is not equal to zero (n is odd), we append 0 to the answer list.\n- The maximum value is equal to ```n//2```; and the minimum value is equal to ```-n//2```.\n- So, we use a ```for``` loop; and each time we add ```-i``` and ```i``` to the answer list. \n\n\n# Python3 code:\n# \n```\n L, rem = n // 2, n % 2\n if rem != 0: ans = [0]\n else: ans = []\n for i in range(1,L+1):\n ans.append(-i)\n ans.append(i) \n return ans\n```
| 40 | 2 |
['Python', 'Python3']
| 7 |
find-n-unique-integers-sum-up-to-zero
|
VERY SIMPLE C++ CODE-
|
very-simple-c-code-by-nisarg1406-lsol
|
DO UPVOTE IF YOU FIND IT USEFUL\n\nCODE - \n\nvector<int> sumZero(int n) {\n\t\tvector<int> res;\n if(n == 0) return res;\n if(n%2 != 0) res.push_
|
nisarg1406
|
NORMAL
|
2020-08-29T04:43:02.565726+00:00
|
2020-08-29T04:43:28.873953+00:00
| 2,202 | false |
**DO UPVOTE IF YOU FIND IT USEFUL**\n\nCODE - \n```\nvector<int> sumZero(int n) {\n\t\tvector<int> res;\n if(n == 0) return res;\n if(n%2 != 0) res.push_back(0); //if odd then to push 0\n for(int i=1;i<=floor(n/2);i++){\n res.push_back(i);\n res.push_back(-i);\n }\n return res;\n}\n```
| 26 | 1 |
['C', 'C++']
| 1 |
find-n-unique-integers-sum-up-to-zero
|
Easy to understand javascript beginner friendly
|
easy-to-understand-javascript-beginner-f-0ons
|
\n\nvar sumZero = function(n) {\n var num = Math.floor(n/2); \n var res = [];\n\n for(var i=1;i<=num;i++){\n res.push(i,-i)\n } \n\n if(n%2!==0){\n
|
yutoliho
|
NORMAL
|
2020-01-03T00:37:57.480330+00:00
|
2020-01-03T00:37:57.480364+00:00
| 2,426 | false |
\n```\nvar sumZero = function(n) {\n var num = Math.floor(n/2); \n var res = [];\n\n for(var i=1;i<=num;i++){\n res.push(i,-i)\n } \n\n if(n%2!==0){\n res.push(0)\n }\n \n return res \n}\n```
| 24 | 1 |
['JavaScript']
| 2 |
find-n-unique-integers-sum-up-to-zero
|
[Java/Python 3] 2 codes / language.
|
javapython-3-2-codes-language-by-rock-qso8
|
Method 1:\njava\n public int[] sumZero(int n) {\n int[] ans = new int[n];\n for (int start = 0, end = n - 1; start < end; ++start, --end) {\n
|
rock
|
NORMAL
|
2019-12-29T04:17:26.564681+00:00
|
2019-12-29T14:47:23.190887+00:00
| 1,971 | false |
**Method 1:**\n```java\n public int[] sumZero(int n) {\n int[] ans = new int[n];\n for (int start = 0, end = n - 1; start < end; ++start, --end) {\n ans[start] = -end;\n ans[end] = end;\n }\n return ans;\n }\n```\n```python\n def sumZero(self, n: int) -> List[int]:\n ans = [0] * n\n start, end = 0, n - 1 \n while start < end:\n ans[start], ans[end] = -end, end\n start, end = start + 1, end - 1 \n return ans\n```\n----\n\n**Method 2: 5 and 1 liners - check odd/even.**\n```java\n public int[] sumZero(int n) {\n int[] ans = new int[n];\n for (int i = -n / 2, k = 0; i <= n / 2; ++i)\n if (i != 0 || n % 2 != 0)\n ans[k++] = i;\n return ans;\n }\n```\n```python\n def sumZero(self, n: int) -> List[int]:\n return [i for i in range((1 - n) // 2, n // 2 + 1) if i != 0 or n % 2 != 0]\n```
| 18 | 3 |
[]
| 2 |
find-n-unique-integers-sum-up-to-zero
|
Brain dead approach. Extendable to non zero sum. Beats 100% || Java
|
brain-dead-approach-extendable-to-non-ze-s0c7
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\nYou want ANY array? You will literally get just ANY array!\n\n# Approach\n Describe
|
pradyot21
|
NORMAL
|
2024-06-16T16:36:26.223938+00:00
|
2024-06-16T16:36:26.223971+00:00
| 1,050 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nYou want $$ANY$$ array? You will literally get just $$ ANY$$ array!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nThe idea probably can\'t get simpler than this.\nWe know the resultant array will be of size *n*. Create an `int` array of size n.\n\n-> Loop until the last element and fill the array with natural numbers. 1, 2, 3, 4, 5 ..... n - 1\n\nWe know that the sum has to be zero. For that to be true, the last element must cancel out the sum of all precending numbers, so we keep a running total while we were iterating above.\n\nHence, last element will be negative of this running total. That\'s it!\n \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nO(n) since we need to iterate once for n-1 elements.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nLikely a constant since we aren\'t using any other space but an integer sum. Can assume to be O(1)\n\n# Code\n```\nclass Solution {\n public int[] sumZero(int n) {\n int[] result = new int[n];\n int sum = 0;\n\n for (int i = 0; i < n-1; i++) {\n result[i] = i+1;\n sum += result[i];\n }\n result[n - 1] = -1 * sum;\n return result;\n }\n\n}\n```\n\nYou can extend this to a non zero sum by just adjusting the last element by the required value of the sum. Say you are asked for n elements whose sum is 21, then the last element can be `(-1*sum) + 21`\n\n\nPlease let me know if there are any questions.
| 15 | 0 |
['Array', 'Math', 'Java']
| 6 |
find-n-unique-integers-sum-up-to-zero
|
[Java] 0 ms, faster than 100.00% of Java online submissions
|
java-0-ms-faster-than-10000-of-java-onli-9pnz
|
```\nclass Solution {\n public int[] sumZero(int n) {\n \n \n int[] ans = new int[n];\n for(int i=0; i<n; i++) {\n ans
|
anuragbhu
|
NORMAL
|
2020-03-19T14:57:54.453615+00:00
|
2020-03-19T15:03:59.914115+00:00
| 1,813 | false |
```\nclass Solution {\n public int[] sumZero(int n) {\n \n \n int[] ans = new int[n];\n for(int i=0; i<n; i++) {\n ans[i] = (i*2)-n+1;\n }\n return ans;\n }\n}
| 15 | 0 |
['Java']
| 5 |
find-n-unique-integers-sum-up-to-zero
|
Two Solutions in Python 3 (one line) (beats 100%) (24 ms)
|
two-solutions-in-python-3-one-line-beats-vz05
|
Asymmetric List: (e.g. [1,2,3,4,5,-15])\n\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n return list(range(1,n))+[-n*(n-1)//2]\n\t\t\n\n
|
junaidmansuri
|
NORMAL
|
2019-12-29T04:03:49.596115+00:00
|
2019-12-29T04:17:16.140242+00:00
| 2,101 | false |
_Asymmetric List:_ (e.g. [1,2,3,4,5,-15])\n```\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n return list(range(1,n))+[-n*(n-1)//2]\n\t\t\n\n```\n_Symmetric List:_ (e.g. [-2,-1,0,1,2] or [-3,-2,-1,1,2,3])\n```\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n return list(range(-(n//2), 0)) + [0]*(n % 2) + list(range(1, n//2 + 1))\n\n \n- Junaid Mansuri\n- Chicago, IL
| 14 | 0 |
['Python', 'Python3']
| 2 |
find-n-unique-integers-sum-up-to-zero
|
C++ || Easy || Explained || ✅
|
c-easy-explained-by-tridibdalui04-znnb
|
1. run a loop from 1 to n/2\n### 2. add -i and i in ans vector so that sum can be 0 at end\n#### 3. if size is given odd add 0 to the vector\n\n\n\nclass Solut
|
tridibdalui04
|
NORMAL
|
2022-10-19T12:30:23.717481+00:00
|
2022-10-19T12:30:23.717522+00:00
| 889 | false |
### 1. run a loop from 1 to n/2\n### 2. add -i and i in ans vector so that sum can be 0 at end\n#### 3. if size is given odd add 0 to the vector\n\n\n```\nclass Solution {\npublic:\n vector<int> sumZero(int n) {\n vector<int>ans;\n for(int i=1;i<=n/2;i++)\n {\n ans.push_back(-i);\n ans.push_back(i);\n }\n if(n%2==1)\n ans.push_back(0);\n return ans;\n }\n};\n```
| 12 | 0 |
['Array', 'C']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
Java || easy to understand || faster than 100% || simple answer.
|
java-easy-to-understand-faster-than-100-pfk2i
|
\nclass Solution {\n public int[] sumZero(int n) {\n \n int[] ans = new int[n];\n int start = 0;\n int end = n - 1;\n \n
|
iamridoydey
|
NORMAL
|
2022-10-09T11:43:12.585540+00:00
|
2022-10-09T11:43:12.585584+00:00
| 1,623 | false |
```\nclass Solution {\n public int[] sumZero(int n) {\n \n int[] ans = new int[n];\n int start = 0;\n int end = n - 1;\n \n while(start < end){\n ans[start] = start + 1;\n ans[end] = ans[start] * (-1);\n start++;\n end--;\n }\n \n return ans;\n \n }\n}\n```
| 12 | 0 |
['Array', 'Java']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
Swift: Find N Unique Integers Sum up to Zero
|
swift-find-n-unique-integers-sum-up-to-z-nfu6
|
swift\nclass Solution {\n func sumZero(_ n: Int) -> [Int] {\n if n <= 1 && 1000 >= n { return [0] }\n var sum = [Int](repeating: 0, count: n)\n
|
AsahiOcean
|
NORMAL
|
2021-04-08T20:49:49.148081+00:00
|
2021-04-08T21:54:22.291456+00:00
| 477 | false |
```swift\nclass Solution {\n func sumZero(_ n: Int) -> [Int] {\n if n <= 1 && 1000 >= n { return [0] }\n var sum = [Int](repeating: 0, count: n)\n for i in 1...(n >> 1) {\n sum[i-1] = i\n sum[n-i] = -i\n }\n return sum\n }\n}\n```
| 12 | 1 |
['Swift']
| 1 |
find-n-unique-integers-sum-up-to-zero
|
Fast python
|
fast-python-by-travelxcodes-jqse
|
\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n a=[]\n if n%2!=0:\n a.append(0)\n for i in range(1,n,2):\n
|
travelXcodes
|
NORMAL
|
2022-11-01T04:01:25.909746+00:00
|
2022-11-01T04:01:25.909784+00:00
| 960 | false |
```\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n a=[]\n if n%2!=0:\n a.append(0)\n for i in range(1,n,2):\n a.append(i)\n a.append(i*(-1))\n return a\n```
| 11 | 0 |
[]
| 0 |
find-n-unique-integers-sum-up-to-zero
|
Java: fast, clean and short - symmetric array handles both parities
|
java-fast-clean-and-short-symmetric-arra-31km
|
Intuition: We can solve this by using pairs of opposites counting away from zero starting with 1, -1 then 2, -2, etc. If we have an odd sized array, we can add
|
mattihito
|
NORMAL
|
2022-05-13T07:04:17.489864+00:00
|
2022-10-27T02:55:15.851467+00:00
| 424 | false |
**Intuition**: We can solve this by using pairs of opposites counting away from zero starting with 1, -1 then 2, -2, etc. If we have an odd sized array, we can add a zero. But what if we like the idea of our array being sorted for easier readability? We can count the left side up starting at -n/2 and increasing left to right, and at the same time, count the right side down starting at n/2 and decreasing right to left.\n\n**Trick**: If we compute half n, and we fill the left side of the array up from -n/2 and fill the right side of the array down from n/2, and if n is even, we are done. But if n is odd, the middle element is already zero from array initialization, and we don\'t have to check it or modify it. Either way, we can do n/2 loop elements and fill from the left and right edges and ignore the odd middle element if there is one. It will already be zero which we want. One less branch is always nice (and can make our code significantly faster when avoided in a loop).\n\n```\nclass Solution {\n\n public int[] sumZero(int n) {\n final int[] answer = new int[n];\n final int halfn = n / 2;\n for (int i = 0; i < halfn; i++) {\n answer[i] = i - halfn; // left increasing: count up from -n/2\n answer[n - i - 1] = halfn - i; // right decreasing: count down from n/2\n }\n\t\t// if n is odd, we filled only n-1 values, but the middle value initialized to 0 and we leave it as-is.\n return answer;\n }\n\n}\n```\n\n**Complexity**: O(n) time, O(1) additional space (O(n) total space including the array for the answer).\n\n**Standard Plea**: If you liked this solution or at least weren\'t annoyed by reading it, **I\'d be glad to have your upvote**. If you didn\'t like it, I\'d love some **constructive feedback in a comment** so I can write better solutions.\n\nThanks, and happy coding!
| 11 | 0 |
['Java']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
Python Solution, Super fast and simple
|
python-solution-super-fast-and-simple-by-zb43
|
\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n a=[]\n if n%2!=0:\n a.append(0)\n for i in range(1,n):\n
|
excalibur12
|
NORMAL
|
2020-06-02T02:12:41.423263+00:00
|
2020-06-02T02:12:41.423312+00:00
| 1,200 | false |
```\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n a=[]\n if n%2!=0:\n a.append(0)\n for i in range(1,n):\n if len(a)==n:\n break\n a.append(i)\n a.append(-i)\n return a\n```
| 9 | 1 |
['Python']
| 2 |
find-n-unique-integers-sum-up-to-zero
|
C++ 100% solution in 3 lines
|
c-100-solution-in-3-lines-by-xzcvbzfgefd-zy0b
|
its just a basic arithmetic series. the ans vector is initialized with the negative sum of all integers up to n - 2. The positive sum can be derived from the in
|
xzcvbzfgefd
|
NORMAL
|
2020-05-29T00:30:13.447653+00:00
|
2020-05-29T00:31:04.290885+00:00
| 1,203 | false |
its just a basic arithmetic series. the ans vector is initialized with the negative sum of all integers up to n - 2. The positive sum can be derived from the integers attained in the loop. These two sets cancel out each other resulting in a total sum of 0.\n\nclass Solution {\npublic:\n vector<int> sumZero(int n) { \n vector<int> ans = {-(n - 2) * (n - 1) / 2}; \n for (int i = 0; i < n - 1; i++)\n ans.push_back(i);\n return ans;\n }\n};
| 9 | 3 |
['C']
| 1 |
find-n-unique-integers-sum-up-to-zero
|
JAVA 100% FASTER and EASY Solution with EXPLANATION
|
java-100-faster-and-easy-solution-with-e-tdni
|
JAVA SOLUTION @DeepakKumar\n# In Case of Any Doubt Feel Free to ASK ...\n\n\nclass Solution {\n public int[] sumZero(int n) {\n// Declaring Size of Array of
|
Deepak2002
|
NORMAL
|
2021-11-02T15:03:30.477393+00:00
|
2021-11-02T15:03:30.477460+00:00
| 708 | false |
# JAVA SOLUTION @DeepakKumar\n# In Case of Any Doubt Feel Free to ASK ...\n\n```\nclass Solution {\n public int[] sumZero(int n) {\n// Declaring Size of Array of SIZE n\n int [] resultantArray = new int[n];\n int num = 1; // Start Numbers to Fill from 1\n int start = 0; // Take Start index at 0\n int end = resultantArray.length-1; // Take last Index as n-1\n while(start<end){ // Fill the Array till Start < end\n /*\n Here Note n --> Can be Even or ODD\n n -> EVEN \n Example n = 2\n Index --> 0 1\n [ 0, 0 ]\n Here / \\ \n Start End --> AT the end these will filled by [+x, -x] i.e Symmetric Numbers\n n -> ODD \n Example n = 3\n Index --> 0 1 2\n [ 0, 0, 0 ]\n Here / \\ \n Start End --> AT the end these will filled by [+x, -x] i.e Symmetric Numbers\n --> Here Note that Loop will go till Start < end\n --> But the Mid is Already 0 \n --> Symmetric numbers will cancel Each other in Sum and gives 0 \n --> Hence, 0+0 = 0 \n */\n resultantArray[start] = num; // Fill Start with positive Number +x\n resultantArray[end] = (-num); // Fill End with negative Number -x\n num++; // Increment the Number Because for Next Numbers Because Numbers must be UNIQUE in ARRAY\n start++; // Increment Start\n end--; // Decrement END\n }\n // At the END return the Resultant Array \n return resultantArray;\n \n }\n}\n```
| 8 | 0 |
['Java']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
C++ 0 ms Faster than 100% of submissions
|
c-0-ms-faster-than-100-of-submissions-by-f90s
|
\nclass Solution {\npublic:\n vector<int> sumZero(int n) {\n int sum = 0;\n int cnt = 1;\n vector<int> v(n,0);\n for (int i = 0;
|
tempatron
|
NORMAL
|
2020-09-13T11:29:52.356052+00:00
|
2020-09-13T11:30:04.888314+00:00
| 1,045 | false |
```\nclass Solution {\npublic:\n vector<int> sumZero(int n) {\n int sum = 0;\n int cnt = 1;\n vector<int> v(n,0);\n for (int i = 0; i < n ; ++i) {\n if (i != n-1) {\n v[i] = cnt;\n sum += v[i];\n cnt++;\n } else {\n v[i] = -sum;\n }\n }\n return v;\n }\n};\n```
| 8 | 0 |
['C']
| 1 |
find-n-unique-integers-sum-up-to-zero
|
[Python] Simple Solution. Key is to not overthink. (32ms, 14MB)
|
python-simple-solution-key-is-to-not-ove-rrxs
|
The key is to not overthink things. As the problem said, you can return any list.\n\nWe only want to iterate until n // 2 because we want half to be positive an
|
seankala
|
NORMAL
|
2020-08-26T09:17:04.770651+00:00
|
2020-08-26T09:17:04.770693+00:00
| 575 | false |
The key is to not overthink things. As the problem said, you can return __*any*__ list.\n\nWe only want to iterate until `n // 2` because we want half to be positive and the other half to be negative integers (excluding 0). For every positive integer, just add its negative counterpart.\n\nIf `n` is an odd number, just add an extra 0 to the end. Problem solved.\n\n````Python\ndef sumZero(n):\n result = []\n \n for i in range(n // 2):\n result.append(i + 1)\n result.append((-1) * (i + 1))\n \n if n % 2 == 1:\n result.append(0)\n \n return result\n````
| 8 | 0 |
['Python', 'Python3']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
Two JS Solutions
|
two-js-solutions-by-hbjorbj-j4zf
|
\n/*\nWe can simply add 1 to n-1 and keep track of this array sum and add the negation of that.\n*/\nvar sumZero = function(n) {\n let sum = 0, res = [];\n
|
hbjorbj
|
NORMAL
|
2020-03-30T21:48:17.897318+00:00
|
2021-05-19T12:15:37.857069+00:00
| 872 | false |
```\n/*\nWe can simply add 1 to n-1 and keep track of this array sum and add the negation of that.\n*/\nvar sumZero = function(n) {\n let sum = 0, res = [];\n for (let i = 1; i < n; i++) {\n res.push(i);\n sum += i;\n }\n res.push(-sum);\n return res;\n // T.C: O(N)\n // S.C: O(N)\n};\n```\n\n```\n/*\nWe add pairs of numbers (num, -num) starting from 1 and ending at floor(n/2).\nIf n is odd, we add 0.\n*/\nvar sumZero = function(n) {\n let res = n % 2 === 0 ? [] : [0];\n for (let i = 1; i <= Math.floor(n/2); i++) {\n res.push(i, -i);\n }\n return res;\n // T.C: O(N)\n // S.C: O(N)\n}\n```
| 8 | 0 |
['JavaScript']
| 3 |
find-n-unique-integers-sum-up-to-zero
|
Easy Peasy Python Solution ^_^
|
easy-peasy-python-solution-_-by-oshine_c-rrvy
|
Intuition\nHere we get two cases:\nCase 1: \nIf number of elements is odd.\nWe will add a zero at the beginning and rest of the elements will be negative and po
|
oshine_chan
|
NORMAL
|
2023-07-31T08:27:44.795716+00:00
|
2023-08-02T18:35:01.353308+00:00
| 471 | false |
# Intuition\nHere we get two cases:\nCase 1: \nIf number of elements is odd.\nWe will add a zero at the beginning and rest of the elements will be negative and postive integers of ceiling(n/2).\n\nCase 2:\nIf number of elements is even.\nWe will directly add the elements that will be negative and postive integers of ceiling(n/2).\n\n\n# Code\n```\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n ans=[]\n nums= int(n/2)\n if n%2!=0:\n ans.append(0)\n for i in range(1,nums+1):\n ans.append(i)\n ans.append(-i)\n return ans\n```\n\n\n
| 7 | 0 |
['Python3']
| 3 |
find-n-unique-integers-sum-up-to-zero
|
JAVA 100% faster solution
|
java-100-faster-solution-by-bathija111-pyp2
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe most important thing to remember here is that when we initialize array in JAVA all
|
bathija111
|
NORMAL
|
2023-01-23T07:09:42.148009+00:00
|
2023-01-23T07:09:42.148041+00:00
| 1,186 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe most important thing to remember here is that when we initialize array in JAVA all the elements are set to zero initially.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn this approach we are setting two elements in a single iteration. First we set i-1 to positive i value and i to negative i value which cancels each other and increment i by 2. Now even when n is odd we only set even number of elements and the remaining one element in the end is already "Zero" so it does not affect the solution.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] sumZero(int n) {\n int[] answer = new int[n];\n for (int i = 1; i<n; i+=2) {\n answer[i-1]=i;\n answer[i]=-i;\n }\n return answer;\n }\n}\n```
| 7 | 0 |
['Java']
| 1 |
find-n-unique-integers-sum-up-to-zero
|
JAVA || 100% FASTER || USING IF / ELSE CONDITION.
|
java-100-faster-using-if-else-condition-96ii7
|
Upvote this solution, if you like it, that will make me happy.\nHappy Learning\n\n\n# Code\n\nclass Solution {\n public int[] sumZero(int n) {\n int[]
|
sharforaz_rahman
|
NORMAL
|
2022-11-30T05:48:26.501614+00:00
|
2022-11-30T05:48:26.501659+00:00
| 1,226 | false |
Upvote this solution, if you like it, that will make me happy.\nHappy Learning\n\n\n# Code\n```\nclass Solution {\n public int[] sumZero(int n) {\n int[] new_array = new int[n];\n\n int length_for_even = n / 2;\n int length_for_odd = n / 2;\n if (n % 2 != 0) {\n\n for (int i = 1, j = 0; i <= length_for_odd; i++, j++) {\n new_array[j] = i * (-1);\n }\n for (int i = 1, j = length_for_odd + 1; i <= length_for_even; i++, j++) {\n new_array[j] = i;\n }\n } else {\n\n for (int i = 1, j = 0; i <= length_for_odd; i++, j++) {\n new_array[j] = i * (-1);\n }\n for (int i = 1, j = length_for_odd; i <= length_for_even; i++, j++) {\n new_array[j] = i;\n }\n }\n return new_array;\n }\n}\n```
| 7 | 0 |
['Java']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
Easy Python Solution (using range function) - faster + less memory than 95%
|
easy-python-solution-using-range-functio-o1k1
|
\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n first_part = list(range(1, n))\n second_part = -sum(first_part)\n return f
|
ibizak
|
NORMAL
|
2021-06-10T13:22:08.456371+00:00
|
2021-06-10T13:22:08.456417+00:00
| 353 | false |
```\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n first_part = list(range(1, n))\n second_part = -sum(first_part)\n return first_part + [second_part]\n \n```
| 7 | 0 |
['Array', 'Python']
| 1 |
find-n-unique-integers-sum-up-to-zero
|
✅REALLY easy solution✅
|
really-easy-solution-by-parijdev-924s
|
\n# Code\n\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n mass = []\n if n % 2 != 0:\n mass.append(0)\n for i i
|
parijdev
|
NORMAL
|
2024-03-24T18:16:12.238012+00:00
|
2024-03-24T18:16:12.238043+00:00
| 378 | false |
\n# Code\n```\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n mass = []\n if n % 2 != 0:\n mass.append(0)\n for i in range(n):\n if len(mass) != n:\n mass.append(-i-1)\n mass.append(i+1)\n return mass\n```\n\n\n
| 6 | 0 |
['Python3']
| 2 |
find-n-unique-integers-sum-up-to-zero
|
C++ and C# very easy solution.100% faster.
|
c-and-c-very-easy-solution100-faster-by-d9ztw
|
\n\nC++ []\nclass Solution {\npublic:\n vector<int> sumZero(int n) {\n vector<int> answer(n);\n int x;\n if(n%2==0){\n x=n/2;\n
|
aloneguy
|
NORMAL
|
2023-04-16T18:21:27.983608+00:00
|
2023-04-16T18:21:27.983679+00:00
| 1,319 | false |
\n\n```C++ []\nclass Solution {\npublic:\n vector<int> sumZero(int n) {\n vector<int> answer(n);\n int x;\n if(n%2==0){\n x=n/2;\n answer[n-1]=0;\n }\n else\n x=(n-1)/2; \n for(int i=1;i<=x;i++){ \n answer[i-1]=-1*i; \n answer[i-1+x]=i;\n }\n return answer; \n }\n};\n```\n```C# []\npublic class Solution {\n public int[] SumZero(int n) {\n int[] answer=new int[n];\n int x;\n if(n%2==0){\n x=n/2;\n answer[n-1]=0;\n }\n else\n x=(n-1)/2; \n for(int i=1;i<=x;i++){ \n answer[i-1]=-1*i; \n answer[i-1+x]=i;\n }\n return answer;\n }\n}\n```\n\n\n\n\n
| 6 | 0 |
['Math', 'C++', 'C#']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
[Swift] Faster than 100%
|
swift-faster-than-100-by-blackbirdng-86q2
|
<- Please vote if my solution was helpful to you.\n\nclass Solution {\n func sumZero(_ n: Int) -> [Int] {\n var result = [Int]()\n var sum = 0\
|
blackbirdNG
|
NORMAL
|
2021-08-01T17:09:37.182322+00:00
|
2021-08-01T17:11:45.098941+00:00
| 159 | false |
<- Please vote if my solution was helpful to you.\n```\nclass Solution {\n func sumZero(_ n: Int) -> [Int] {\n var result = [Int]()\n var sum = 0\n for i in 1..<n {\n result.append(i)\n sum += i\n }\n result.append(-sum)\n return result\n }\n}\n```\n
| 6 | 0 |
['Swift']
| 1 |
find-n-unique-integers-sum-up-to-zero
|
1304 | JavaScript 1-Line Solution
|
1304-javascript-1-line-solution-by-spork-suu9
|
Now updated to work with the newly discovered integer "2".\n\n> Runtime: 74 ms, faster than 69.44% of JavaScript online submissions\n> Memory Usage: 44.3 MB, le
|
sporkyy
|
NORMAL
|
2020-03-02T18:07:07.308647+00:00
|
2022-04-26T20:53:57.602439+00:00
| 629 | false |
Now updated to work with the newly discovered integer "2".\n\n> Runtime: **74 ms**, faster than *69.44%* of JavaScript online submissions\n> Memory Usage: **44.3 MB**, less than *5.61%* of JavaScript online submissions\n\n```javascript\n/**\n * @param {number} n\n * @return {number[]}\n */\nconst sumZero = n => [...new Array(n).keys(), ((1 - n) * n) / 2].slice(1);\n```
| 6 | 0 |
['JavaScript']
| 4 |
find-n-unique-integers-sum-up-to-zero
|
[Python 3]. Simple. O(n). 28ms
|
python-3-simple-on-28ms-by-rohin7-x9l0
|
Explanation:\n* Return an arithmetic progression with common difference 2, centered around 0\n\n\nclass Solution:\n def sumZero(self, n):\n result=[]\
|
rohin7
|
NORMAL
|
2019-12-29T05:41:34.790260+00:00
|
2019-12-29T05:54:44.723492+00:00
| 1,071 | false |
Explanation:\n* Return an arithmetic progression with common difference 2, centered around 0\n\n```\nclass Solution:\n def sumZero(self, n):\n result=[]\n _int_=-n+1\n for i in range(n):\n result.append(_int_)\n _int_=_int_+2\n return result\n```
| 6 | 2 |
['Python', 'Python3']
| 3 |
find-n-unique-integers-sum-up-to-zero
|
C++||Easy to Understand
|
ceasy-to-understand-by-return_7-9lpq
|
```\nclass Solution {\npublic:\n vector sumZero(int n) \n {\n vector ans(n);\n for(int i=0;i<n;i++)\n {\n ans[i]=i*2-n+1;\
|
return_7
|
NORMAL
|
2022-09-13T19:46:16.017323+00:00
|
2022-09-13T19:46:16.017366+00:00
| 237 | false |
```\nclass Solution {\npublic:\n vector<int> sumZero(int n) \n {\n vector<int> ans(n);\n for(int i=0;i<n;i++)\n {\n ans[i]=i*2-n+1;\n }\n return ans;\n \n }\n};\n//if you like the solution plz upvote.
| 5 | 0 |
['C']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
Java Simple Easy Math
|
java-simple-easy-math-by-himanshu_pandey-o2t5
|
```class Solution {\n public int[] sumZero(int n) {\n int[] result =new int[n];\n int i=0;\n for ( i=0; i< n-1;i++){\n result[
|
Himanshu_Pandey1995
|
NORMAL
|
2022-04-21T05:44:49.738666+00:00
|
2022-04-21T05:44:49.738712+00:00
| 230 | false |
```class Solution {\n public int[] sumZero(int n) {\n int[] result =new int[n];\n int i=0;\n for ( i=0; i< n-1;i++){\n result[i]=i-n;\n result[i+1]=n-i;\n i++;\n }\n return result;\n }\n}
| 5 | 0 |
['Java']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
Find N Unique Integers Sum up to Zero | Simple Java Solution | Beats 100%
|
find-n-unique-integers-sum-up-to-zero-si-lsf1
|
We have to fill the array with equal number of Postive and Negative numbers. Example: if the value of n is 4, then we can have a array [-1, 1, -2, 2]. If "n" is
|
deleted_user
|
NORMAL
|
2021-08-29T14:04:55.145546+00:00
|
2021-09-02T13:23:51.747112+00:00
| 297 | false |
We have to fill the array with equal number of Postive and Negative numbers. Example: if the value of n is 4, then we can have a array [-1, 1, -2, 2]. If "n" is odd, we will add \'0\' to the array. Example: n = 5, then we can have na array with the following values [-1, 1, -2, 2, 0]\n\n```\nclass Solution {\n public int[] sumZero(int n) {\n int [] result = new int [n];\n \n\t\t// We will add one Positive and one negative number.\n\t\t// We have the condition "n-1", so if the value of \'n\' is odd, we wont fill the last cell of the result array. It will be 0 by default.\n for (int index = 0; index < n - 1; index += 2) {\n result [index] = index + 1;\n result [index + 1] = - (index + 1);\n }\n \n return result;\n }\n}\n```
| 5 | 0 |
['Java']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
Java solution, faster than 100%
|
java-solution-faster-than-100-by-optimal-8csj
|
class Solution {\n public int[] sumZero(int n) {\n \n\t\tint[] res = new int[n];\n \n int cur = 0;\n if(n%2!=0) {\n res
|
optimalsis
|
NORMAL
|
2020-04-10T02:29:56.615417+00:00
|
2020-04-10T02:29:56.615473+00:00
| 321 | false |
class Solution {\n public int[] sumZero(int n) {\n \n\t\tint[] res = new int[n];\n \n int cur = 0;\n if(n%2!=0) {\n res[cur] = 0;\n cur++;\n }\n \n for(int i=1; i<=n/2; i++) {\n res[cur++] = i;\n res[cur++] = -i;\n }\n \n return res;\n }\n}
| 5 | 1 |
[]
| 2 |
find-n-unique-integers-sum-up-to-zero
|
Simple Java Solution
|
simple-java-solution-by-mugdhagovilkar11-bs01
|
\nclass Solution {\n public int[] sumZero(int n) {\n int[] ans = new int[n];\n int num = n/2;\n int index = 0;\n while(num>0)\n
|
mugdhagovilkar1197
|
NORMAL
|
2020-01-09T03:26:03.384783+00:00
|
2020-01-09T03:26:03.384851+00:00
| 456 | false |
```\nclass Solution {\n public int[] sumZero(int n) {\n int[] ans = new int[n];\n int num = n/2;\n int index = 0;\n while(num>0)\n {\n ans[index++] = num;\n ans[index++] = num*-1;\n num--;\n }\n if(n%2 == 1)\n ans[index++] = 0;\n return ans;\n \n }\n}\n```
| 5 | 0 |
['Java']
| 1 |
find-n-unique-integers-sum-up-to-zero
|
JavaScript Solution
|
javascript-solution-by-ehdwn1212-gbsq
|
js\nvar sumZero = function(n) {\n const uniqueIntegers = [];\n const half = parseInt(n / 2);\n \n for (let i = 1; i <= half; i++) {\n uniqueI
|
ehdwn1212
|
NORMAL
|
2020-01-06T16:43:31.275727+00:00
|
2020-01-06T16:43:31.275775+00:00
| 703 | false |
```js\nvar sumZero = function(n) {\n const uniqueIntegers = [];\n const half = parseInt(n / 2);\n \n for (let i = 1; i <= half; i++) {\n uniqueIntegers.push(i);\n uniqueIntegers.push(-i);\n }\n \n if (n % 2) {\n uniqueIntegers.push(0);\n }\n \n return uniqueIntegers;\n};\n```
| 5 | 0 |
['JavaScript']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
One Line Rust Solution
|
one-line-rust-solution-by-wfxr-sx3k
|
rust\npub fn sum_zero(n: i32) -> Vec<i32> {\n\t(1 - n..n).step_by(2).collect()\n}\n
|
wfxr
|
NORMAL
|
2019-12-31T02:07:31.568002+00:00
|
2019-12-31T02:07:31.568058+00:00
| 90 | false |
```rust\npub fn sum_zero(n: i32) -> Vec<i32> {\n\t(1 - n..n).step_by(2).collect()\n}\n```
| 5 | 0 |
[]
| 1 |
find-n-unique-integers-sum-up-to-zero
|
C# Solution
|
c-solution-by-leonhard_euler-tf05
|
\npublic class Solution \n{\n public int[] SumZero(int n) \n {\n var result = new List<int>();\n for(int i = 1; i <= n/2; i++)\n {\n
|
Leonhard_Euler
|
NORMAL
|
2019-12-29T04:57:51.542216+00:00
|
2019-12-29T04:58:03.905175+00:00
| 736 | false |
```\npublic class Solution \n{\n public int[] SumZero(int n) \n {\n var result = new List<int>();\n for(int i = 1; i <= n/2; i++)\n {\n result.Add(i);\n result.Add(-i);\n }\n \n if(n % 2 == 1) result.Add(0);\n return result.ToArray();\n }\n}\n```
| 5 | 0 |
[]
| 3 |
find-n-unique-integers-sum-up-to-zero
|
The most simplest way
|
the-most-simplest-way-by-nurzhansultanov-3lye
|
\n\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n result = []\n if n%2==0:\n for i in range(1,(n//2)+1):\n
|
NurzhanSultanov
|
NORMAL
|
2024-02-06T17:11:00.140312+00:00
|
2024-02-06T17:11:00.140334+00:00
| 412 | false |
\n```\nclass Solution:\n def sumZero(self, n: int) -> List[int]:\n result = []\n if n%2==0:\n for i in range(1,(n//2)+1):\n result.append(i)\n result.append((-1)*i)\n result.sort()\n return result\n else:\n for i in range(1,((n-1)//2)+1):\n result.append(i)\n result.append((-1)*i)\n result.append(0)\n result.sort()\n return result\n```
| 4 | 0 |
['Python3']
| 0 |
find-n-unique-integers-sum-up-to-zero
|
BEATS 100%
|
beats-100-by-nitish_reddy27-8mvg
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
nitish_reddy27
|
NORMAL
|
2023-07-29T08:25:04.371192+00:00
|
2023-07-29T08:31:12.449755+00:00
| 823 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] sumZero(int n) {\n int[] ans=new int[n];\n if(n==1){\n ans[n-1]=0;\n return ans;\n }\n int temp=0;\n if(n%2==0) temp=n;\n if(n%2!=0){\n temp=n-1;\n ans[n-1]=0;\n }\n for(int i=0;i<temp;i+=2){\n ans[i]=i+1;\n ans[i+1]=-(i+1);\n }\n return ans;\n }\n}\n```
| 4 | 0 |
['Java']
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.