Maximum Profit

ARRAY
DYNAMIC PROGRAMMING

Problem

Given an array prices where prices[i] represents the price of a stock on the i-th day, determine the maximum profit you can achieve by making at most two transactions.

A transaction is buying and then selling one share of the stock, and you cannot engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Examples

maxProfit([7,8,0,4,3,6]) // returns 7 /* Day 2 (0) -> Buy Day 3 (4) -> Sell = +4 Day 4 (3) -> Buy Day 5 (6) -> Sell = +3 Profit = 4 + 3 = 7 */ maxProfit([1,2,3,4]) // returns 3 /* Day 0 (1) -> Buy Day 3 (4) -> Sell = +3 Profit = 3 */
Loading...