Split array into three equal sum segments
Input: arr[] = [1, 3, 4, 0, 4]
Output: [1, 2]
Explanation: 3 equal sum segments are: arr[0...1], arr[2...2] and arr[3...4] each having sum = 4.Input: arr[] = [2, 3, 4]
Output: [-1, -1]
Explanation: No three segments exist which has equal sum.Input: arr[] = [1, -1, 1, -1, 1, -1, 1, -1]
Output: [1, 3]
Explanation: 3 equal sum segments are: arr[0...1], arr[2...3] and arr[4...7] each having sum = 0.
class gfg{
public int[] findIndex(int[] arr){
int n = arr.length;
int tot = 0;
int[] res = new int[2];
for(int i = 0; i<n;i++){
tot += arr[i];
}
if(tot % 3 != 0){
res[0] = -1;
res[1] = -1;
return res;
}
int resInd = 0;
int curSum = ;
for(int i =0;i<n;i++){
curSum += arr[i]
if(curSum == tot/3){
curSum = 0;
res[resInd++] = i
if(resInd == 2 && i < n-1) {
return res;
}
}
}
res[0] = -1;
res[1] = -1;
return res;
}
}
Comments
Post a Comment