You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
Example 1
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 1 (price = 1) and sell on day 2 (price = 5) for +4, then buy on day 3 (price = 3) and sell on day 4 (price = 6) for +3. The total profit is 4 + 3 = 7.
Example 2
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 0 (price = 1) and sell on day 4 (price = 5) for a profit of 4. Trading every day (+1 four times) gives the same total.
Example 3
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: Prices only fall, so any trade loses money. The best profit is 0.
Since you can trade freely, capture every price increase: any multi-day rise can be decomposed into consecutive one-day gains. So just add up every positive difference between consecutive days.
Run checks all cases above. Submit evaluates all test cases.