Maximize Greatness of an Array — two pointers
On a sorted array the pair that sums to target is found by walking inward. Built for LeetCode 2592. Maximize Greatness of an Array.
If the current sum is too small, the only way to grow it is to advance lo. If it is too big, retreat hi. Each step discards an index forever, so the walk is linear.
Algorithm
- Set
lo = 0,hi = n−1. - While
lo < hi, comparenums[lo] + nums[hi]totarget. - Equal → return the indices. Too small →
lo++. Too big →hi--.
- Time
- O(n)
- Space
- O(1)
Assumes the array is sorted.
class Solution: def maximizeGreatnessOfAnArray(self, nums: list[int], target: int) -> list[int]: lo, hi = 0, len(nums) - 1 while lo < hi: s = nums[lo] + nums[hi] if s == target: return [lo, hi] if s < target: lo += 1 else: hi -= 1 return []