-
Notifications
You must be signed in to change notification settings - Fork 0
/
Split_array_in_three_equal_sum_subarrays.cpp
89 lines (74 loc) · 2.18 KB
/
Split_array_in_three_equal_sum_subarrays.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
// Class Solution to contain the method for solving the problem.
class Solution {
public:
// Function to determine if array arr can be split into three equal sum sets.
vector<int> findSplit(vector<int>& arr) {
// code here
vector<int> ans;
int sum = 0;
int t_sum = 0;
for(auto it : arr) sum += it;
if(sum % 3 != 0) return {-1, -1};
sum /= 3;
for(int i = 0; i < arr.size(); i++)
{
t_sum += arr[i];
if(t_sum == sum)
{
ans.push_back(i);
if(ans.size() == 2) break;
t_sum = 0;
}
}
if(ans.size() == 2) return ans;
return {-1, -1};
}
};
//{ Driver Code Starts.
int main() {
int test_cases;
cin >> test_cases;
cin.ignore();
while (test_cases--) {
string input;
vector<int> arr;
// Read the array from input line
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
// Solution instance to invoke the function
Solution ob;
vector<int> result = ob.findSplit(arr);
// Output result
if (result[0] == -1 && result[1] == -1 || result.size() != 2) {
cout << "false" << endl;
} else {
int sum1 = 0, sum2 = 0, sum3 = 0;
for (int i = 0; i < arr.size(); i++) {
if (i <= result[0])
sum1 += arr[i];
else if (i <= result[1])
sum2 += arr[i];
else
sum3 += arr[i];
}
if (sum1 == sum2 && sum2 == sum3) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
}
cout << "~" << endl;
}
return 0;
}
// } Driver Code Ends