709987. Hit most Balloons

Medium

Hit most Balloons Slug: hit-most-balloons--170637 Difficulty: Medium Id: 709987 Topic Tags: Mathematical, Geometric, Algorithms Company Tags: PayPal

Summary

The "Hit most Balloons" problem requires you to find the maximum number of balloons that can be hit from a given set of positions. The problem involves mathematical and geometric concepts, such as calculating the distance between two points and determining the optimal position to hit the most balloons.

Detailed Explanation

The problem can be approached by iterating through each possible position and calculating the number of balloons that can be hit from that position. The key is to find the maximum number of balloons that can be hit without hitting any balloon more than once.

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

  1. Initialize a variable maxHit to keep track of the maximum number of balloons that can be hit.
  2. Iterate through each possible position i.
  3. For each position i, calculate the distance between i and each balloon using the formula distance = abs(i - balloon).
  4. Sort the distances in descending order.
  5. Initialize a variable hit to 0, which will keep track of the number of balloons hit from the current position i.
  6. Iterate through the sorted distances and for each distance, check if there is a balloon that can be hit at that distance. If there is, increment hit by 1.
  7. Update maxHit with the maximum value between maxHit and hit.
  8. Return maxHit, which represents the maximum number of balloons that can be hit.

Time complexity: O(n log n) due to sorting Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public class HitMostBalloons {
    public static int hitMostBalloons(int[] positions, int[] balloons) {
        Arrays.sort(positions);
        int maxHit = 0;
        for (int position : positions) {
            int hit = 0;
            for (int balloon : balloons) {
                if (Math.abs(balloon - position) <= distanceToNextBalloon(balloon, positions)) {
                    hit++;
                }
            }
            maxHit = Math.max(maxHit, hit);
        }
        return maxHit;
    }

    private static int distanceToNextBalloon(int balloon, int[] positions) {
        for (int i = positions.length - 1; i > 0; i--) {
            if (positions[i] >= balloon) {
                return positions[i] - balloon;
            }
        }
        return Integer.MAX_VALUE;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.