Advertisement
satishfrontenddev5

Untitled

Jan 18th, 2024
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * @param {number[]} arr
  3.  * @return {boolean}
  4.  */
  5. var canThreePartsEqualSum = function(arr) {
  6.         var oneThird = sum / 3,
  7.         p1 = 0,
  8.         p2 = A.length - 1,
  9.         sum1 = 0,
  10.         sum2 = sum,
  11.         sum3 = 0;
  12.    
  13.     while (p1<p2 && (sum1 !== oneThird || sum2 !== oneThird)) {
  14.         if (sum1!==oneThird) {
  15.             sum1 += A[p1]
  16.             sum2 -= A[p1] //sliding window
  17.             p1++
  18.         }
  19.         if (sum3!==oneThird) {
  20.             sum3 += A[p2]
  21.             sum2 -= A[p2]
  22.             p2--
  23.         }      
  24.      
  25.     }
  26.  
  27.      return sum1 === sum2 && sum2 === sum3 // this line could have more efficient alternatives
  28.    
  29. };
  30.  
  31.  
  32.  
  33.  
  34. cpp:
  35. class Solution {
  36. public:
  37.     bool canThreePartsEqualSum(vector<int>& arr) {
  38.         //prefix sum with two pointers
  39.         for(int i=1;i<arr.size();i++)
  40.         {
  41.             arr[i]+=arr[i-1];
  42.         }
  43.         int total=arr.back();
  44.         if(total%3!=0) return false;
  45.         int sum=total/3;
  46.        
  47.         int i=0,j=arr.size()-2;
  48.         while(i<j)
  49.         {
  50.             while(i<j && arr[i]!=sum) i++;
  51.             while(j>i && total-arr[j]!=sum) j--;
  52.             if(i<j && arr[j]-arr[i]==sum) return true;
  53.             i++;
  54.             j--;
  55.         }
  56.         return false;
  57.     }
  58. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement