712029. Maximum Stone Removal

Medium

Maximum Stone Removal

Slug: maximum-stone-removal-1662179442 Difficulty: Medium Id: 712029

Summary

The Maximum Stone Removal problem is about finding the maximum number of stones that can be removed from a given sequence of stones. The stones are arranged in an alternating pattern (i.e., one stone, then another, and so on) with different weights. The goal is to remove the heaviest stones to maximize the total weight of the remaining stones.

Detailed Explanation

The problem can be solved by using a greedy approach. We start by considering the first two stones. Since we need to alternate between heavy and light stones, we choose the heavier stone (if it exists) or the lighter one (if both are equal). This is because removing the heavier stone gives us more weight in total.

Now, let's consider the next pair of stones. We repeat the same process: choose the heavier stone if possible, or the lighter one if both are equal. By doing this for all pairs of stones, we get the maximum number of stones that can be removed and the resulting total weight.

Here is a step-by-step breakdown of the solution:

  1. Initialize two variables, maxWeight and count, to store the maximum weight and count of removed stones, respectively.
  2. Iterate through the sequence of stones in pairs (i.e., one stone at a time).
  3. For each pair, check if the heavier stone is available. If it is, remove it and increment the count.
  4. If both stones in the pair are equal or there is no heavier stone, remove the lighter stone.
  5. Update maxWeight by adding the weight of the removed stone to the total weight.
  6. Repeat steps 2-5 until all stones have been processed.
  7. Return maxWeight as the maximum weight of the remaining stones.

Time complexity: O(n), where n is the number of stones in the sequence. Space complexity: O(1), since we only use a constant amount of space to store variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxStoneRemoval(int[] stones) {
    int maxWeight = 0;
    int count = 0;
    for (int i = 0; i < stones.length; i += 2) {
        if (stones[i] > stones[i + 1]) {
            maxWeight += stones[i];
            count++;
        } else {
            maxWeight += stones[i + 1];
        }
    }
    return maxWeight;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.