-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathBalance Array
More file actions
107 lines (64 loc) · 1.38 KB
/
Balance Array
File metadata and controls
107 lines (64 loc) · 1.38 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
Problem Description
Given an integer array A of size N. You need to count the number of special elements in the given array.
A element is special if removal of that element make the array balanced.
Array will be balanced if sum of even index element equal to sum of odd index element.
Problem Constraints
1 <= N <= 105
1 <= A[i] <= 109
Input Format
First and only argument is an integer array A of size N.
Output Format
Return an integer denoting the count of special elements.
Example Input
Input 1:
A = [2, 1, 6, 4]
Input 2:
A = [5, 5, 2, 5, 8]
Example Output
Output 1:
1
Output 2:
2
Example Explanation
Explanation 1:
After deleting 1 from array : {2,6,4}
(2+4) = (6)
Hence 1 is the only special element, so count is 1
Explanation 2:
If we delete A[0] or A[1] , array will be balanced
(5+5) = (2+8)
So A[0] and A[1] are special elements, so count is 2.
#####solution####
int Solution::solve(vector<int> &A) {
long long n=A.size(),p=0,q=0;
for(int i=0;i<n;i++){
if(i%2==0){
p+=A[i];
}
else{
q+=A[i];
}
}
long long ans=0,x=0,y=0;
for(int i=0;i<n;i++){
long long x1=0,y1=1;
if(i%2==0){
p-=A[i];
}
else{
q-=A[i];
}
x1=x+q;
y1=y+p;
if(x1==y1){
ans++;
}
if(i%2==0){
x+=A[i];
}
else{
y+=A[i];
}
}
return ans;
}