TwoPointer

Template

11. Container With Most Water

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Example:

Input: [1,8,6,2,5,4,8,3,7] Output: 49

  • 受制於比較矮的那一邊

  • The shorter line's pointer might find higher line to overcome the reduction in area caused by the width reduction.

public int maxArea(int[] height) {
    int i=0, j=height.length-1;
    int max = Integer.MIN_VALUE;
    while(i<j){
        if(height[i] < height[j]){
            max = Math.max(max, height[i]*(j-i));
            i++;
        }else{
            max = Math.max(max, height[j]*(j-i));
            j--;
        }
    }
    return max;

42 Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

Solution [https://leetcode.com/problems/trapping-rain-water/solution/]

  1. DP

    • Record the highest point so far from left to right and right to left.

    • sum += min(left[i], right[i]) - height[i]

    • Time O(n), Space O(n)

  2. Two Pointer

    • 在最高點左邊,trap只會受到leftMax影響。反之,在最高點右邊,trap只會受到rightMax影響

    • twoPointer從左右逐漸向最高點逼近

407. Trapping Rain Water II

Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.

  • Greedy + minHeap

  • Put boundary heights in minHeap, starting from the lowest boundary

  • Update current height, traverse 4 directions

  • Add to answer whenever we can see nextHeight < currentHeight

768. Max Chunks To Make Sorted II

769 with duplicate number

  • Store the max from left and store the min from left

  • A pivot point is at the point minRight[i+1] >= maxMin[i]

769. Max Chunks To Make Sorted

Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], split the array into chunks, and individually sort each chunk. After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

  • Use index as sorted answer array to match the current array

  • Take the max number as pivot point

Last updated

Was this helpful?