Skip to content

2576. Find the Maximum Number of Marked Indices 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  int maxNumOfMarkedIndices(vector<int>& nums) {
    ranges::sort(nums);

    int l = 0;
    int r = nums.size() / 2 + 1;

    while (l < r) {
      const int m = (l + r) / 2;
      if (isPossible(nums, m))
        l = m + 1;
      else
        r = m;
    }

    return (l - 1) * 2;
  }

 private:
  bool isPossible(const vector<int>& nums, int m) {
    for (int i = 0; i < m; ++i)
      if (2 * nums[i] > nums[nums.size() - m + i])
        return false;
    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
  public int maxNumOfMarkedIndices(int[] nums) {
    Arrays.sort(nums);

    int l = 0;
    int r = nums.length / 2 + 1;

    while (l < r) {
      final int m = (l + r) / 2;
      if (isPossible(nums, m))
        l = m + 1;
      else
        r = m;
    }

    return (l - 1) * 2;
  }

  private boolean isPossible(int[] nums, int m) {
    for (int i = 0; i < m; ++i)
      if (2 * nums[i] > nums[nums.length - m + i])
        return false;
    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def maxNumOfMarkedIndices(self, nums: list[int]) -> int:
    nums.sort()

    def isPossible(m: int) -> bool:
      for i in range(m):
        if 2 * nums[i] > nums[-m + i]:
          return False
      return True

    l = bisect.bisect_left(range(len(nums) // 2 + 1), True,
                           key=lambda m: not isPossible(m))
    return (l - 1) * 2

Approach 2: Linear

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int maxNumOfMarkedIndices(vector<int>& nums) {
    ranges::sort(nums);

    int i = 0;
    for (int j = nums.size() / 2; j < nums.size(); ++j)
      if (2 * nums[i] <= nums[j] && ++i == nums.size() / 2)
        break;

    return i * 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int maxNumOfMarkedIndices(int[] nums) {
    Arrays.sort(nums);

    int i = 0;
    for (int j = nums.length / 2; j < nums.length; ++j)
      if (2 * nums[i] <= nums[j] && ++i == nums.length / 2)
        break;

    return i * 2;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maxNumOfMarkedIndices(self, nums: list[int]) -> int:
    nums.sort()

    i = 0
    for j in range(len(nums) // 2, len(nums)):
      if 2 * nums[i] <= nums[j]:
        i += 1
        if i == len(nums) // 2:
          break

    return i * 2