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.
Great...At least you are using Stack...The solution from
uplinksandy9 is ok, but actually use Prefix Sum Array here is not so efficient due take time reverting every array twice. On the other hand, it does not matter if the problem could be done in other way, we could try using real Stack (the problem is under Stack topic). Here my solution using custom Node and LinkedList for simulate Stack.
public class Solution {
static class Node {
public int sumTillHere;
public int value;
public Node(int value, int sumTillHere) {
this.sumTillHere = sumTillHere;
this.value = value;
}
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
String[] lengths = cin.nextLine().split(" ");
int N1 = Integer.parseInt(lengths[0]);
int N2 = Integer.parseInt(lengths[1]);
int N3 = Integer.parseInt(lengths[2]);
LinkedList<Node> list1 = new LinkedList<>();
LinkedList<Node> list2 = new LinkedList<>();
LinkedList<Node> list3 = new LinkedList<>();
int sumTillNode = 0;
int value = 0;
String[] line1 = cin.nextLine().split(" ");
String[] line2 = cin.nextLine().split(" ");
String[] line3 = cin.nextLine().split(" ");
for (int i = N1 - 1; i >= 0; i--) {
value = Integer.parseInt(line1[i]);
sumTillNode += value;
list1.push(new Node(value, sumTillNode));
}
sumTillNode = 0;
for (int i = N2 - 1; i >= 0; i--) {
value = Integer.parseInt(line2[i]);
sumTillNode += value;
list2.push(new Node(value, sumTillNode));
}
sumTillNode = 0;
for (int i = N3 - 1; i >= 0; i--) {
value = Integer.parseInt(line3[i]);
sumTillNode += value;
list3.push(new Node(value, sumTillNode));
}
System.out.println(equalStacks(list1, list2, list3));
}
static int equalStacks(LinkedList<Node> list1, LinkedList<Node> list2, LinkedList<Node> list3) {
while (true) {
if (list1.isEmpty() || list2.isEmpty() || list3.isEmpty()) {
return 0;
}
if (list1.peek().sumTillHere == list2.peek().sumTillHere && list2.peek().sumTillHere == list3.peek().sumTillHere) {
break;
}
if (list1.peek().sumTillHere > list2.peek().sumTillHere) {
list1.pop();
}
if (list2.peek().sumTillHere > list3.peek().sumTillHere) {
list2.pop();
}
if (list3.peek().sumTillHere > list1.peek().sumTillHere) {
list3.pop();
}
}
return list1.peek().sumTillHere;
}
Equal Stacks
You are viewing a single comment's thread. Return to all comments →
Great...At least you are using Stack...The solution from uplinksandy9 is ok, but actually use Prefix Sum Array here is not so efficient due take time reverting every array twice. On the other hand, it does not matter if the problem could be done in other way, we could try using real Stack (the problem is under Stack topic). Here my solution using custom Node and LinkedList for simulate Stack.
public class Solution {
}