Find the Maximum Number of Marked Indices - Problem

You are given a 0-indexed integer array nums.

Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:

  • Pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j], then mark i and j.

Return the maximum possible number of marked indices in nums using the above operation any number of times.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,5,2,4]
Output: 2
💡 Note: We can mark indices 2 and 3 since 2 * nums[2] = 2 * 2 = 4 ≤ nums[3] = 4. No other valid pairs exist.
Example 2 — Multiple Pairs Possible
$ Input: nums = [1,3,2,4]
Output: 2
💡 Note: We can mark indices 0 and 1 since 2 * nums[0] = 2 * 1 = 2 ≤ nums[1] = 3. Alternatively, we could mark indices 2 and 3 since 2 * nums[2] = 2 * 2 = 4 ≤ nums[3] = 4. Both give 2 marked indices.
Example 3 — No Valid Pairs
$ Input: nums = [7,6,8]
Output: 0
💡 Note: No pair (i,j) exists where 2 * nums[i] ≤ nums[j], so no indices can be marked.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Maximum Number of Marked Indices INPUT nums = [3, 5, 2, 4] 3 i=0 5 i=1 2 i=2 4 i=3 Sorted: [2, 3, 4, 5] 2 3 4 5 Condition: 2*nums[i] <= nums[j] ALGORITHM STEPS 1 Sort Array Sort nums ascending 2 Two Pointers left=0, right=n/2 3 Greedy Match Match small with large 4 Count Pairs Return 2 * pairs found Matching Process: 2 3 4 5 2*2=4 <= 4 OK FINAL RESULT Marked Indices: 2 OK 3 4 OK 5 Output: 2 1 valid pair found: (2, 4) where 2*2 <= 4 Total marked = 2 Note: (3,5) invalid since 2*3=6 > 5 Key Insight: After sorting, use two pointers: small elements (first half) match with large elements (second half). Greedy approach: pair smallest available with smallest valid partner. This maximizes total pairs. Time: O(n log n) for sorting | Space: O(1) extra space TutorialsPoint - Find the Maximum Number of Marked Indices | Optimized Greedy with Binary Search
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
285 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen