If the total sum of the array is not divisible by 3, it’s impossible to split it into three equal parts. Otherwise, we can scan the array and count how many times we reach a running sum equal to one third of the total. If we can do this at least twice before the end, the array can be partitioned as required.
classSolution {
public:bool canThreePartsEqualSum(vector<int>& arr) {
int total = accumulate(arr.begin(), arr.end(), 0);
if (total %3!=0) return false;
int target = total /3, sum =0, cnt =0;
for (int i =0; i < arr.size(); ++i) {
sum += arr[i];
if (sum == target) {
++cnt;
sum =0;
}
}
return cnt >=3;
}
};
classSolution {
publicbooleancanThreePartsEqualSum(int[] arr) {
int total = 0;
for (int v : arr) total += v;
if (total % 3 != 0) returnfalse;
int target = total / 3, sum = 0, cnt = 0;
for (int v : arr) {
sum += v;
if (sum == target) {
cnt++;
sum = 0;
}
}
return cnt >= 3;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funcanThreePartsEqualSum(arr: IntArray): Boolean {
val total = arr.sum()
if (total % 3!=0) returnfalseval target = total / 3var sum = 0var cnt = 0for (v in arr) {
sum += v
if (sum == target) {
cnt++ sum = 0 }
}
return cnt >=3 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defcanThreePartsEqualSum(self, arr: list[int]) -> bool:
total = sum(arr)
if total %3!=0:
returnFalse target = total //3 s = cnt =0for v in arr:
s += v
if s == target:
cnt +=1 s =0return cnt >=3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfncan_three_parts_equal_sum(arr: Vec<i32>) -> bool {
let total: i32= arr.iter().sum();
if total %3!=0 { returnfalse; }
let target = total /3;
let (mut sum, mut cnt) = (0, 0);
for&v in&arr {
sum += v;
if sum == target {
cnt +=1;
sum =0;
}
}
cnt >=3 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
canThreePartsEqualSum(arr: number[]):boolean {
consttotal=arr.reduce((a, b) =>a+b, 0);
if (total%3!==0) returnfalse;
consttarget=total/3;
letsum=0, cnt=0;
for (constvofarr) {
sum+=v;
if (sum===target) {
cnt++;
sum=0;
}
}
returncnt>=3;
}
}