-
Notifications
You must be signed in to change notification settings - Fork 0
/
Equilibrium_Point.java
114 lines (107 loc) · 2.82 KB
/
Equilibrium_Point.java
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
108
109
110
111
112
113
114
/*Question: Equilibrium Point.
Link:-https://practice.geeksforgeeks.org/problems/equilibrium-point-1587115620/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).
Input: n = 1 A[] = {1}.
Output: 1
Explanation: Since its the only element hence its the only equilibrium point.
Input: n = 2 A[] = {26,26}.
Output: -1
Explanation: Since there cannot be any midpoint.
*/
public class Equilibrium_Point {
public static int equilibriumPoint(long arr[], int n) {
int leftsum=(int)arr[0];
int rightsum=(int)arr[n-1];
int s=1;
int l=n-2;
if(n==1){
return 1;
}
if(n==2 && leftsum==rightsum){
return -1;
}
while(s<l){
if(leftsum<rightsum){
leftsum+=arr[s];
s++;
}else{
rightsum+=arr[l];
l--;
}
}
if(leftsum!=rightsum){
return -1;
}
return s+1;
}
static int leftSum(long arr[],int l){
int lsum=0;
int i=0;
// {1,3,5,2,2};
while(i<l){
lsum+=arr[i];
i++;
}
return lsum;
}
static int rightSum(long arr[], int r){
int rsum=0;
int l=arr.length;
// {1,3,5,2,2};
while(r<l){
rsum+=arr[r];
r++;
}
return rsum;
}
/*Another way for the solution */
// Function to find equilibrium point in the array.
// static int leftSum(long arr[],int l){
// int lsum=0;
// int i=0;
// while(i<l){
// lsum+=arr[i];
// i++;
// }
// return lsum;
// }
// static int rightSum(long arr[], int r){
// int rsum=0;
// int l=arr.length;
// while(r<l){
// rsum+=arr[r];
// r++;
// }
// return rsum;
// }
// public static int equilibriumPoint(long arr[], int n) {
// int sum1=0,sum2=0;
// if(n==1){
// // int ans=(int)arr[0];
// return 1;
// }
// // if(n==2 && arr[0]==arr[1]){
// // return -1;
// // }
// int i=0;
// while(i<n){
// int l=leftSum(arr,i+1);
// // System.out.println(l);
// int r=rightSum(arr,i+2);
// // System.out.print(l+" "+r);
// // System.out.println();
// if(l==r){
// return i+2;
// }
// i++;
// }
// return -1;
// }
public static void main(String[] args) {
long[] arr={1,3,5,2,2};
int n=arr.length;
System.out.println(equilibriumPoint(arr, n));
}
}