Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @param {number[]} arr
- * @return {boolean}
- */
- var canThreePartsEqualSum = function(arr) {
- var oneThird = sum / 3,
- p1 = 0,
- p2 = A.length - 1,
- sum1 = 0,
- sum2 = sum,
- sum3 = 0;
- while (p1<p2 && (sum1 !== oneThird || sum2 !== oneThird)) {
- if (sum1!==oneThird) {
- sum1 += A[p1]
- sum2 -= A[p1] //sliding window
- p1++
- }
- if (sum3!==oneThird) {
- sum3 += A[p2]
- sum2 -= A[p2]
- p2--
- }
- }
- return sum1 === sum2 && sum2 === sum3 // this line could have more efficient alternatives
- };
- cpp:
- class Solution {
- public:
- bool canThreePartsEqualSum(vector<int>& arr) {
- //prefix sum with two pointers
- for(int i=1;i<arr.size();i++)
- {
- arr[i]+=arr[i-1];
- }
- int total=arr.back();
- if(total%3!=0) return false;
- int sum=total/3;
- int i=0,j=arr.size()-2;
- while(i<j)
- {
- while(i<j && arr[i]!=sum) i++;
- while(j>i && total-arr[j]!=sum) j--;
- if(i<j && arr[j]-arr[i]==sum) return true;
- i++;
- j--;
- }
- return false;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement