Skip to content

Commit

Permalink
Create Split array in three equal sum subarrays
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Nov 28, 2024
1 parent 5f4e142 commit 45e946a
Showing 1 changed file with 95 additions and 0 deletions.
95 changes: 95 additions & 0 deletions Split array in three equal sum subarrays
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//Split array in three equal sum subarrays

import java.io.*;
import java.util.*;

class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testCases = Integer.parseInt(br.readLine().trim());

while(testCases-- > 0) {
String[] str = br.readLine().trim().split(" ");
int[] arr = new int[str.length];

for(int i = 0; i < str.length; i++) {
arr[i] = Integer.parseInt(str[i]);
}

Solution ob = new Solution();
List<Integer> result = ob.findSplit(arr);

if(result.get(0) == -1 && result.get(1) == -1 || result.size() != 2) {
System.out.println("false");
}
else {
int sum1 = 0, sum2 = 0, sum3 = 0;

for(int i = 0; i < arr.length; i++) {
if(i <= result.get(0)) {
sum1 += arr[i];
}
else if (i <= result.get(1)) {
sum2 += arr[i];
}
else {
sum3 += arr[i];
}
}

if(sum1 == sum2 && sum2 == sum3) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
System.out.println("~");
}
}
}

class Solution {
public List<Integer> findSplit(int[] arr) {
List<Integer> res = new ArrayList<>();
int n = arr.length;
int resIdx = 0;
int total = 0;

if(arr.length == 0) {
return new ArrayList<>();
}

for(int i = 0; i < n; i++) {
total += arr[i];
}

if(total % 3 != 0) {
res.add(-1);
res.add(-1);

return res;
}

int currSum = 0;

for(int i = 0; i < n; i++) {
currSum += arr[i];

if(currSum == total / 3) {
currSum = 0;
res.add(i);
resIdx++;

if(resIdx == 2 && i < n - 1) {
return res;
}
}
}

res.add(-1);
res.add(-1);

return res;
}
}

0 comments on commit 45e946a

Please sign in to comment.