709993. Max Equal sum of 3 Stacks
Medium
Max Equal sum of 3 Stacks
Slug: find-maximum-equal-sum-of-three-stacks
Difficulty: Medium
Id: 709993
Topic Tags: Greedy, Stack, Data Structures, Algorithms
Company Tags: None
Summary
Given three stacks A, B, and C with their respective sizes n1, n2, and n3. We need to find the maximum equal sum of the three stacks. If it's not possible to have an equal sum for all three stacks, return -1.
Detailed Explanation
To solve this problem, we will iterate through each stack and add elements until one of the stacks has a sum that is less than or equal to the others. We then calculate the maximum possible sum by subtracting the smallest element from the other two stacks. The maximum equal sum will be the minimum of these sums.
Here's a step-by-step breakdown:
- Initialize variables
max_sumandmin_sumto 0. - Iterate through each stack:
- For each stack, add elements until one of the stacks has a sum that is less than or equal to the others.
- Calculate the maximum possible sum by subtracting the smallest element from the other two stacks.
- Update
max_sumandmin_sumwith the calculated values. - Return the minimum of
max_sumandmin_sum.
Optimized Solutions
Java
public class Main {
public static int maxEqualSum(int[] a, int[] b, int[] c) {
int sumA = 0, sumB = 0, sumC = 0;
for (int i : a) {
sumA += i;
}
for (int i : b) {
sumB += i;
}
for (int i : c) {
sumC += i;
}
int maxSum = Math.max(sumA, Math.max(sumB, sumC));
int minSum = Integer.MAX_VALUE;
if (sumA > 0 && sumB > 0 && sumC > 0) {
for (int i : a) {
int temp = sumA - i;
if (temp <= Math.min(sumB, sumC)) {
maxSum = temp;
break;
}
}
}
return (maxSum == minSum) ? maxSum : -1;
}
public static void main(String[] args) {
int[] a = {5, 4, 6};
int[] b = {7, 8, 9};
int[] c = {10, 11, 12};
System.out.println(maxEqualSum(a, b, c));
}
}