We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
/*
* Complete the 'equalStacks' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER_ARRAY h1
* 2. INTEGER_ARRAY h2
* 3. INTEGER_ARRAY h3
*/
public static int equalStacks(List<Integer> h1, List<Integer> h2, List<Integer> h3) {
int sum1 = h1.stream().mapToInt(Integer::intValue).sum();
int sum2 = h2.stream().mapToInt(Integer::intValue).sum();
int sum3 = h3.stream().mapToInt(Integer::intValue).sum();
int i = 0, j = 0, k = 0;
// Loop until we find equal sums or exhaust one of the stacks
while (i < h1.size() && j < h2.size() && k < h3.size()) {
// If all three sums are equal, return the sum
if (sum1 == sum2 && sum1 == sum3) {
return sum1;
}
// Remove the top element from the tallest stack
if (sum1 >= sum2 && sum1 >= sum3) {
sum1 -= h1.get(i++);
} else if (sum2 >= sum1 && sum2 >= sum3) {
sum2 -= h2.get(j++);
} else if (sum3 >= sum1 && sum3 >= sum2) {
sum3 -= h3.get(k++);
}
}
return 0;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
Equal Stacks
You are viewing a single comment's thread. Return to all comments →
Java soloution
import java.io.; import java.util.; import java.util.stream.*;
import static java.util.stream.Collectors.toList;
class Result {
}
public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
}