Prefix Sum problem Equilibrium point GFG
public class EqulibriumPoint {
// More efficient solution
public static boolean getTruth(int[] arr) {
int n = arr.length;
int totalSum = 0;
for(int i = 0; i < n; i++) {
totalSum += arr[i];
}
int lSum = 0;
for(int i = 0; i < n; i++) {
if(lSum == totalSum - arr[i]) {
return true;
}
lSum += arr[i];
totalSum -= arr[i];
}
return false;
}
// Finding equlibrium point
public static int[] prefixSum(int[] arr){
int n = arr.length;
int[] array = new int[n];
int sum = 0;
for(int i = 0; i < n; i++){
sum += arr[i];
array[i] = sum;
}
return array;
}
public static boolean getEquilibrium(int[] arr) {
int n = arr.length;
int[] array = new int[n];
array = prefixSum(arr);
for(int i = 1; i < n; i++) {
if(array[i - 1] == array[n - 1] - array[i]) {
return true;
}
if(array[n - 1] - array[0] == 0 || array[n - 2] == 0) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] array = {2,-2,4,2,-2,0};
System.out.println(getTruth(array));
}
}
Comments
Post a Comment