Here's an interesting coding puzzle:

A trader can perform two buys and two sells in a day of a given stock. An array of positive integers represents the share price of this stock at different times of the day (index i = 0 represents hour 1, i=1 represents hour 2, etc). The trader must always sell any current shares he has before he buys more shares. Write a function that determines the maximum profit the trader can make by buying and selling stock for a given day.

int maximizeProfit(int[] prices) {
   // Your code here
}

ex:
[10, 22, 5, 75, 65, 80]
The maximum profit is 87: buy at 10 sell at 22, buy at 5, sell at 80.

Open in new window


The solution should have time complexity O(n).
2

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month