-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEquilibriumPoint-GFGQ.cpp
More file actions
99 lines (72 loc) · 1.89 KB
/
EquilibriumPoint-GFGQ.cpp
File metadata and controls
99 lines (72 loc) · 1.89 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
/*
Equilibrium Point
Given an array A of n positive numbers. The task is to find the first Equilibium Point in the array.
Equilibrium Point in an array is a position such that the sum of elements before it is equal to the sum of elements after it.
Note: Retun the index of Equilibrium point. (1-based index)
Example 1:
Input:
n = 5
A[] = {1,3,5,2,2}
Output: 3
Explanation:
equilibrium point is at position 3
as elements before it (1+3) =
elements after it (2+2).
Example 2:
Input:
n = 1
A[] = {1}
Output: 1
Explanation:
Since its the only element hence
its the only equilibrium point.
Your Task:
The task is to complete the function equilibriumPoint() which takes the array and n as input parameters and returns the point of equilibrium. Return -1 if no such point exists.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
Constraints:
1 <= n <= 106
1 <= A[i] <= 108
*/
//{ Driver Code Starts
#include <iostream>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// Function to find equilibrium point in the array.
// a: input array
// n: size of array
int equilibriumPoint(long long a[], int n) {
// Your code here
int pre = 0, post = 0;
for (int i = 0; i < n; i++) post += a[i];
for (int i = 0; i < n; i++) {
post -= a[i];
if (pre == post) return i+1;
pre += a[i];
}
return -1;
}
};
//{ Driver Code Starts.
int main() {
long long t;
//taking testcases
cin >> t;
while (t--) {
long long n;
//taking input n
cin >> n;
long long a[n];
//adding elements to the array
for (long long i = 0; i < n; i++) {
cin >> a[i];
}
Solution ob;
//calling equilibriumPoint() function
cout << ob.equilibriumPoint(a, n) << endl;
}
return 0;
}
// } Driver Code Ends