From 45e946a44a45d63e10709fdc467a1359b9b998c6 Mon Sep 17 00:00:00 2001 From: Disha Thakurata <146114938+dishathakurata@users.noreply.github.com> Date: Thu, 28 Nov 2024 10:33:08 +0530 Subject: [PATCH] Create Split array in three equal sum subarrays --- Split array in three equal sum subarrays | 95 ++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Split array in three equal sum subarrays diff --git a/Split array in three equal sum subarrays b/Split array in three equal sum subarrays new file mode 100644 index 0000000..7b71b13 --- /dev/null +++ b/Split array in three equal sum subarrays @@ -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 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 findSplit(int[] arr) { + List 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; + } +}