Best Time to Buy and Sell Stock

LeetCode problem 121: Best Time to Buy and Sell Stock.

## Problem description

You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` 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 `0`.

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
* `1 <= prices.length <= 105`
* `0 <= prices[i] <= 104`

## 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. `balance` – 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 `INT_MIN`, since we want to keep increasing it during the iterations.
2. `maxProfit` – 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. `balance = std::max(balance, -prices[i])` – 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. `maxProfit = std::max(maxProfit, balance + prices[i])` – 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 `maxProfit` as the result.

### Working example

* Input: 7, 1, 5, 3, 6, 4

 `balance` (after each iteration)
 `maxProfit` (after each iteration)

* 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 `balance` and `maxProfit` 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)**.
## Solution

### C++ solution

```
class Solution {
public:
 int maxProfit(std::vector<int>& prices) {
 const int days = prices.size();
 if (days < 2) {
 return 0;
 }

 int balance = INT\_MIN, maxProfit = 0;
 for (const int& price: prices) {
 balance = std::max(balance, -price);
 maxProfit = std::max(maxProfit, balance + price);
 }

 return maxProfit;
 }
};

```

### Java solution

```
class Solution {
 public int maxProfit(int[] prices) {
 final int days = prices.length;
 if (days < 2) {
 return 0;
 }

 int balance = Integer.MIN\_VALUE, maxProfit = 0;
 for (int price: prices) {
 balance = Math.max(balance, -price);
 maxProfit = Math.max(maxProfit, balance + price);
 }

 return maxProfit;
 }
}

```

## See also

Best time to buy and sell stock
 122
 123
 188
 309
 714