forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request ZoranPandovski#3310 from shivesh41kr/patch-3
Equilibrium Point in an Array
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
//Equilibrium index of an Array using Array-Sum | ||
|
||
#include <bits/stdc++.h> | ||
using namespace std; | ||
|
||
int equilibrium(int arr[], int n) | ||
{ | ||
int sum = 0; // initialize sum of whole array | ||
int leftsum = 0; // initialize leftsum | ||
|
||
/* Find sum of the whole array */ | ||
for (int i = 0; i < n; ++i) | ||
sum += arr[i]; | ||
|
||
for (int i = 0; i < n; ++i) { | ||
sum -= arr[i]; // sum is now right sum for index i | ||
|
||
if (leftsum == sum) | ||
return i; | ||
|
||
leftsum += arr[i]; | ||
} | ||
|
||
/* If no equilibrium index found, then return 0 */ | ||
return -1; | ||
} | ||
|
||
int main() | ||
{ | ||
int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; | ||
int arr_size = sizeof(arr) / sizeof(arr[0]); | ||
|
||
// Function call | ||
cout << "First equilibrium index is " | ||
<< equilibrium(arr, arr_size); | ||
return 0; | ||
} | ||
|
||
/* | ||
Time Complexity: O(N) | ||
Auxiliary Space: O(1) | ||
*/ |