Problem 29
Best Time to Buy and Sell Stock II
Medium · 20 pts · Array, Greedy
Problem
You are given the price of a stock on each of N days. You may make as many trades as you like, but you can hold at most one share at a time, so you must sell before you buy again. You may buy and sell on the same day. Find the maximum total profit. The key observation is that the best strategy collects every price increase: whenever tomorrow's price is higher than today's, that difference can be added to the profit. Summing all positive day-to-day differences gives the answer.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the maximum total profit.
Constraints
1 <= N <= 100000; 0 <= price[i] <= 10000
Example input
6 7 1 5 3 6 4
Example output
7
Explanation
The prices are 7 1 5 3 6 4. Buy at 1 and sell at 5 for +4, then buy at 3 and sell at 6 for +3. The total profit is 4 + 3 = 7.