-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSumStack.java
More file actions
27 lines (22 loc) · 856 Bytes
/
MaxSumStack.java
File metadata and controls
27 lines (22 loc) · 856 Bytes
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
package Greedy;
public class MaxSumStack {
public static int maxEqualSum(int n1, int n2, int n3, int[] stack1, int[] stack2, int[] stack3) {
int sum1 = 0, sum2 = 0, sum3 = 0;
for (int i = 0; i < n1; i++) sum1 += stack1[i];
for (int i = 0; i < n2; i++) sum2 += stack2[i];
for (int i = 0; i < n3; i++) sum3 += stack3[i];
int top1 = 0, top2 = 0, top3 = 0;
int ans = 0;
while (top1 < n1 && top2 < n2 && top3 < n3) {
if (sum1 == sum2 && sum2 == sum3)
return sum1;
if (sum1 >= sum2 && sum1 >= sum3)
sum1 -= stack1[top1++];
else if (sum2 >= sum1 && sum2 >= sum3)
sum2 -= stack2[top2++];
else if (sum3 >= sum2 && sum3 >= sum1)
sum3 -= stack3[top3++];
}
return 0;
}
}