Greedy

经典题目

11 Container With Most Waterarrow-up-right

Maintain a global res. Start from the two ends and move towards the middle using two pointers. Every time we try to increase the height: we pick the lower side, and move that index to the next element, so as to ensure we have the maximum area of current width.

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

134 Gas Stationarrow-up-right

Based on two facts:

  1. if start from A we cannot reach B, then any gas station in the between cannot reach B. (B is the first one cannot reach)

  2. if total gas >= total cost, there must be a solution

621. Task Schedulerarrow-up-right

It's easier to get the number of empty slots first.

885 Boats to Save Peoplearrow-up-right

Last updated