-
Notifications
You must be signed in to change notification settings - Fork 0
/
Split_an_array_into_two_equal_sum_subarray.cpp
93 lines (84 loc) · 1.94 KB
/
Split_an_array_into_two_equal_sum_subarray.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
90
91
92
93
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
bool canSplit(vector<int>& arr) {
int n = arr.size();
int i = 0;
int j = n;
int prefix = 0;
int suffix = 0;
while(i < j)
{
if(prefix < suffix)
{
prefix+= arr[i];
i++;
}
else if(prefix > suffix)
{
suffix += arr[j-1];
j--;
}
else
{
if(i+1 < j)
{
prefix += arr[i];
i++;
suffix += arr[j-1];
j--;
}
else
{
prefix += arr[i];
i++;
}
}
}
if(prefix == suffix) return true;
return false;
}
};
/*
Brute Force :-
bool canSplit(vector<int>& arr) {
int prefix = 0;
int suffix = 0;
int n = arr.size();
for(int i = 0; i < n; i++)
{
prefix += arr[i];
suffix = 0;
for(int j = i+1; j < n; j++)
{
suffix += arr[j];
}
if(prefix == suffix) return true;
}
return false;
}
*/
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t-- > 0) {
string s;
getline(cin, s);
stringstream ss(s);
vector<int> arr;
string temp;
while (ss >> temp) {
arr.push_back(stoi(temp));
}
Solution obj;
bool res = obj.canSplit(arr);
cout << (res ? "true" : "false") << endl;
}
return 0;
}
// } Driver Code Ends