← Back to Tutorials

9. Greedy & Advanced (Days 120—134)

Interval Scheduling (Non-overlapping Intervals)

def eraseOverlapIntervals(intervals):
    intervals.sort(key=lambda x: x[1])
    end = float('-inf')
    count = 0
    for s, e in intervals:
        if s >= end:
            end = e
        else:
            count += 1
    return count

Gas Station

def canCompleteCircuit(gas, cost):
    if sum(gas) < sum(cost): return -1
    tank = start = 0
    for i in range(len(gas)):
        tank += gas[i] - cost[i]
        if tank < 0:
            start = i + 1
            tank = 0
    return start

Trapping Rain Water

// C++ — Two pointers
int trap(vector<int>& height) {
    int l = 0, r = height.size() - 1;
    int leftMax = 0, rightMax = 0, water = 0;
    while (l < r) {
        if (height[l] < height[r]) {
            if (height[l] >= leftMax) leftMax = height[l];
            else water += leftMax - height[l];
            l++;
        } else {
            if (height[r] >= rightMax) rightMax = height[r];
            else water += rightMax - height[r];
            r--;
        }
    }
    return water;
}

More Problems

ProblemPatternComplexity
Partition LabelsLast occurrence, greedy partitionO(n), O(1)
CandyLeft-to-right, right-to-left passesO(n), O(n)
Skyline ProblemMax-heap, sweep lineO(n log n)
✏️ Exercise: Implement Interval Scheduling (non-overlapping), Gas Station, and Trapping Rain Water. Aim to solve all three within 45 min.