-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEquilibrium Point.cpp
42 lines (37 loc) · 1.36 KB
/
Equilibrium Point.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
// Equilibrium Point
// Difficulty: EasyAccuracy: 28.13%Submissions: 613K+Points: 2
// Given an array of integers arr[], the task is to find the first equilibrium point in the array.
// The equilibrium point in an array is an index (0-based indexing) such that the sum of all elements before that index is the same as the sum of elements after it. Return -1 if no such point exists.
// Examples:
// Input: arr[] = [1, 2, 0, 3]
// Output: 2
// Explanation: The sum of left of index 2 is 1 + 2 = 3 and sum on right of index 2 is 0 + 3 = 3.
// Input: arr[] = [1, 1, 1, 1]
// Output: -1
// Explanation: There is no equilibrium index in the array.
// Input: arr[] = [-7, 1, 5, 2, -4, 3, 0]
// Output: 3
// Explanation: The sum of left of index 3 is -7 + 1 + 5 = -1 and sum on right of index 3 is -4 + 3 + 0 = -1.
// Constraints:
// 3 <= arr.size() <= 106
// -109 <= arr[i] <= 109
// Company Tags
// AmazonAdobe
// Topic Tags
// Related Articles
// Expected Complexities
// If you are facing any issue on this page. Please let us know.
int findEquilibrium(vector<int> &arr) {
// code here
int n=arr.size();
int totSum=accumulate(arr.begin(),arr.end(),0);
int leftSum=0;
for(int i=0;i<n;i++){
totSum-=arr[i];
if(totSum==leftSum){
return i;
}
leftSum+=arr[i];
}
return -1;
}