Best Time to Buy and Sell Stock

problem 121: Best Time to Buy and Sell Stock.

Problem description
You are given an array  where   is the price of a given stock on the   day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return.


 * Example 1
 * Input: prices = [7,1,5,3,6,4]
 * Output: 5
 * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.


 * Example 2
 * Input: prices = [7,6,4,3,1]
 * Output: 0
 * Explanation: In this case, no transactions are done and the max profit = 0.


 * Constraints

Problem analysis
A stock transaction has two components: buying and selling. Of course, buying has to occur before selling.

So to find out the maximum profit in one-pass, we can set two variables:
 * 1)   – records the balance at hand when you have completed 0.5 transactions, i.e. after buying the first stock but before selling it out. This variable is initialized to , since we want to keep increasing it during the iterations.
 * 2)   – maximum profit you can accumulate from day 0 to day i, for which we traverse i from left to right. This variable is initialized to 0, which is the profit we would get in the worst case.

Then we traverse each day i from left to right and see how the maximum profit goes. During each iteration we perform the following updates:
 * 1)   – This is to check whether we should purchase the stock on day i. We want it to be as large as possible, i.e. having the absolute value as small as possible. As a result, the smaller the price we purchase, the greater the profit we gain for selling on the same day.
 * 2)   – This is to check whether we can gain greater profit by selling the stock at hand on day i.

Loop until we have covered the last day. Then return  as the result.

Working example

 * Input: 7, 1, 5, 3, 6, 4
 * Return: 5 (buy on day 1 → sell on day 4)

Complexity analysis

 * Time complexity
 * We do the problem one-pass. When iterating on the price of each day, we update the  and   exactly once during each iteration, with O(1) time complexity for each of them. So the total time complexity is O(n), where n is the number of days.


 * Space complexity
 * Since we did not create additional data structures, the space complexity is O(1).