703305. Greater tower sum

Medium

Save Gotham: Greater Tower Sum

Summary

The problem is to find the maximum sum of towers in a given array. The array represents the heights of the towers, and we need to find the maximum sum that can be obtained by considering any subset of these towers.

Tags: Arrays, Stack, Data Structures

Detailed Explanation

To solve this problem, we will use a stack-based approach. We iterate through the array from left to right, and for each tower, we check if it is greater than the top of our current stack (if the stack is not empty). If it is, we pop all elements from the stack that are smaller than the current tower until we find one that is either equal or larger. Then, we push the current tower onto the stack.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty stack.
  2. Iterate through the array:
    • For each tower, check if it is greater than the top of our current stack (if the stack is not empty).
    • If it is, pop all elements from the stack that are smaller than the current tower until we find one that is either equal or larger.
    • Push the current tower onto the stack.
  3. Calculate the sum of all elements in the stack.

Time complexity: O(n), where n is the number of towers. Space complexity: O(n), as we use a stack to store the towers.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Stack;

public class GreaterTowerSum {
    public static int saveGotham(int[] towers) {
        Stack<Integer> stack = new Stack<>();
        int maxSum = 0;
        for (int tower : towers) {
            while (!stack.isEmpty() && stack.peek() < tower) {
                stack.pop();
            }
            stack.push(tower);
            maxSum += stack.size();
        }
        return maxSum;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.