LeetCode 2557: Maximum Number of Integers to Choose From a Range II

Problem Description

Explanation:

Given a range of integers represented by a 2D array ranges, where ranges[i] = [left_i, right_i], we need to find the maximum number of integers that we can choose from the range such that there are no duplicates.

To solve this problem, we can use the following algorithm:

  1. Sort the ranges based on the left boundary of each range.
  2. Initialize a variable result to store the maximum number of integers we can choose.
  3. Iterate through each range and compare the right boundary of the current range with the maximum right boundary we have encountered so far. If the right boundary is greater, update the maximum right boundary and increment result by the difference between the new right boundary and the previous right boundary.
  4. Return the final result.

Time complexity: O(n log n) where n is the number of ranges Space complexity: O(1)

:

Solutions

class Solution {
    public int maxNumberOfApples(int[][] ranges) {
        Arrays.sort(ranges, (a, b) -> Integer.compare(a[0], b[0]));
        
        int result = 0;
        int maxRight = 0;
        
        for (int[] range : ranges) {
            if (range[1] > maxRight) {
                result += Math.min(range[1], range[1]) - maxRight;
                maxRight = range[1];
            }
        }
        
        return result;
    }
}

Loading editor...