#2592
Maximize Greatness of an Array
MediumArrayTwo PointersGreedySortingTwo PointersSortingGreedy
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 leverages sorting and a two-pointer technique. By sorting the array, we can efficiently find the next greater element for each index, maximizing the count of indices where perm[i] > nums[i].
⚙️
Algorithm
4 steps- 1Step 1: Sort the input array nums.
- 2Step 2: Initialize two pointers: one for the sorted array and one for the original array.
- 3Step 3: Iterate through the original array, and for each element, find the smallest unused element in the sorted array that is greater than the current element.
- 4Step 4: If found, increment the count and move both pointers forward.
solution.py9 lines
1def maxGreatness(nums):
2 nums.sort()
3 count = 0
4 j = 0
5 for num in nums:
6 if j < len(nums) and num < nums[j]:
7 count += 1
8 j += 1
9 return countℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(1) since we are modifying the array in place.
- 1Sorting the array allows for efficient comparisons to find the next greater element.
- 2Using two pointers helps to track the current position in both the original and sorted arrays.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.