Problem 671
Minimum Initial Energy to Finish Tasks
Hard · 30 pts · Array, Greedy, Sorting
Problem
Each task i has two numbers: ACTUAL[i], the energy it uses, and MINIMUM[i], the energy you must have to start it (MINIMUM[i] >= ACTUAL[i]). You may do the tasks in any order. Find the minimum starting energy that lets you finish them all. Do the tasks with the largest gap MINIMUM - ACTUAL first. Then compute the answer backwards: going from the last task to the first, the energy needed before a task is max(MINIMUM, ACTUAL + energy needed after it).
Input
The first line contains N. Each of the next N lines contains ACTUAL[i] and MINIMUM[i].
Output
Print the minimum initial energy.
Constraints
1 <= N <= 100000; 1 <= ACTUAL[i] <= MINIMUM[i] <= 10000
Example input
3 1 2 2 4 4 8
Example output
8
Explanation
For tasks (1,2), (2,4) and (4,8), start with 8: do (4,8) leaving 4, then (2,4) leaving 2, then (1,2) leaving 1. Starting with 7 would not even allow the first task, so the answer is 8.