#2576
Find the Maximum Number of Marked Indices
MediumArrayTwo PointersBinary SearchGreedySortingTwo PointersGreedy AlgorithmsSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal approach sorts the array and uses a two-pointer technique to efficiently find pairs that can be marked. This reduces the number of checks needed by leveraging the sorted order.
⚙️
Algorithm
5 steps- 1Step 1: Sort the array nums.
- 2Step 2: Initialize two pointers, one at the start (left) and one at the middle (right) of the sorted array.
- 3Step 3: While both pointers are within bounds, check if 2 * nums[left] <= nums[right]. If true, mark both and move both pointers forward.
- 4Step 4: If the condition is not met, move the left pointer forward to find a larger value.
- 5Step 5: Continue until either pointer goes out of bounds, and return the total marked count.
solution.py18 lines
1# Full working Python code
2
3def maxMarkedIndices(nums):
4 nums.sort()
5 n = len(nums)
6 left, right = 0, n // 2
7 count = 0
8 while left < n // 2 and right < n:
9 if 2 * nums[left] <= nums[right]:
10 count += 2
11 left += 1
12 right += 1
13 else:
14 left += 1
15 return count
16
17# Example usage
18print(maxMarkedIndices([3, 5, 2, 4])) # Output: 2ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the two-pointer traversal is O(n). The space complexity is O(1) since we are not using any additional data structures that grow with input size.
- 1The problem can be efficiently solved by sorting the array and using a two-pointer technique.
- 2The relationship 2 * nums[i] <= nums[j] suggests a pairing strategy where smaller values can be matched with larger values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.