Skip to content

Instantly share code, notes, and snippets.

@rohanjai777
Last active July 15, 2021 23:32
Show Gist options
  • Save rohanjai777/99d4e6ffa48ea599c94704f76c78f9b1 to your computer and use it in GitHub Desktop.
Save rohanjai777/99d4e6ffa48ea599c94704f76c78f9b1 to your computer and use it in GitHub Desktop.
public class Solution {
public int solve(int length, int[] arr) {
int sum = 0;
for(int i=0;i<length;i++){
sum+=arr[i];
}
int avg = sum/3;
if(sum%3 != 0){
return 0;
}
int steps = 0;
ArrayList<Integer> prefix = new ArrayList<>();
ArrayList<Integer> suffix = new ArrayList<>();
int tempsum1 = 0; int tempsum2 = 0;
for(int i=0;i<length;i++){
tempsum1+=arr[i];
if(tempsum1 == avg){
prefix.add(i);
}
}
for(int i=length-1;i>=0;i--){
tempsum2+=arr[i];
if(tempsum2 == avg){
suffix.add(i);
}
}
//System.out.println(suffix);
for(int i=0;i<prefix.size();i++){
for(int j=0;j<suffix.size();j++){
int x = prefix.get(i);
int y = suffix.get(j);
int getsum = 0; boolean flag = false;
for(int k=x+1;k<y;k++){
getsum+=arr[k];
flag = true;
}
if(getsum == avg && flag == true){
steps++;
}
}
}
return steps;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment