LeetCode: Container With Most Water Solution
Approach
The point here is to prove why when h[i] < h[j]
we move i
to the right
By contradiction, if we move j
to the left instead:
- horizontal length will reduce whatever
- if
h[j-1] < h[i]
-> area will beh[j-1] * horizontal length
-> smaller than previous - if
h[j-1] > h[i]
-> area will beh[i] * horizontal length
-> smaller than previous
So there is no way moving j
to the left will produce larger area
Implementation
1/**2 * @param {number[]} height3 * @return {number}4 */5var maxArea = function (height) {6 let i = 07 let j = height.length - 18 let max = -Infinity9 while (i != j) {10 max = Math.max(max, Math.min(height[i], height[j]) * Math.abs(i - j))11 if (height[i] > height[j]) {12 j--13 } else {14 i++15 }16 }17 return max18}
Comments
Loading comments...
Tags
leetcode
array
two pointers
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.