LeetCode121

121. Best Time to Buy and Sell Stock

1. Description:

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

1
2
3
4
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

1
2
3
4
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

2. Difficulty:

Easy

3. Relative Problems:

1
2
3
4
122. Best Time to Buy and Sell Stock II
123. Best Time to Buy and Sell Stock III
188. Best Time to Buy and Sell Stock IV
309. Best Time to Buy and Sell Stock with Cooldown

4. Solution:

Analysis:

( 1 ). We should find a day the stock price is lower than next day price.

1
2
3
e.g.:
8 1 9
It is impossible to get a higher profit if you buy at day1 and sell at day3 instead of buying at day 2, selling at day3.

( 2 ). If the profit < 0. Choose a new day to buy.

1
2
3
4
e.g.:
2 6 1 4 10
It is impossible to get a higher profit if you buy at day1 and sell at day4 or day5.
The best solution is buy at day 3 sell at day 5.

Code

1
2
3
4
5
6
7
int maxProfit = 0;
int cur = 0;
for(int i = 1; i < prices.length; i++){
cur = Math.max(0,cur += prices[i] - prices[i - 1]);
maxProfit = Math.max(maxProfit,cur);
}
return maxProfit;

It is also called Kadane’s Algorithm.