-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Split array in three equal sum subarrays
- Loading branch information
1 parent
5f4e142
commit 45e946a
Showing
1 changed file
with
95 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |