Question
Best Time to Buy and Sell Stock 3
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Input
User Task
Since this is a functional problem, you don't have to input anything. You just need to complete the maxProfit() function that takes an integer array prices as a parameter and returns an integer representing the maximum profit you can achieve.
Custom Input
The first line of the input contains a single integer n, representing the size of the array prices.
The second line of the input contains n space-separated integers representing elements of the array prices.
Since this is a functional problem, you don't have to input anything. You just need to complete the maxProfit() function that takes an integer array prices as a parameter and returns an integer representing the maximum profit you can achieve.
Custom Input
The first line of the input contains a single integer n, representing the size of the array prices.
The second line of the input contains n space-separated integers representing elements of the array prices.
Output
Return an integer representing the maximum profit you can achieve.
Example
Input:
8
3 3 5 0 0 3 1 4
Output:
6
Explanation:
Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Therefore, total profit is 3 + 3 = 6.
8
3 3 5 0 0 3 1 4
Output:
6
Explanation:
Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Therefore, total profit is 3 + 3 = 6.