1013. Partition Array Into Three Parts With Equal Sum

 

Example 1:

Input: arr = [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1

Example 2:

Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false

Example 3:

Input: arr = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

 

Constraints:

  • 3 <= arr.length <= 5 * 104
  • -104 <= arr[i] <= 10 
  • class Solution {
    public boolean canThreePartsEqualSum(int[] arr) {
    int total = 0;
    for(int ele : arr){
    total += ele;
    }
    if(total % 3 != 0) return false;
    int count = 0;
    int sum = 0;
    int target = total/3;
    for(int i = 0;i<arr.length;i++){
    sum += arr[i];
    if(sum == target){
    sum = 0;
    count++;
    }
    }
    return count>=3;
    }
    }
     

Comments

Popular Posts