Greedy
经典题目
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;
}Based on two facts:
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)
if total gas >= total cost, there must be a solution
It's easier to get the number of empty slots first.
Last updated