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 | Input: [7, 1, 5, 3, 6, 4] |
Example 2:
1 | Input: [7, 6, 4, 3, 1] |
2. Difficulty:
Easy
3. Relative Problems:
1 | 122. Best Time to Buy and Sell Stock II |
4. Solution:
Analysis:
( 1 ). We should find a day the stock price is lower than next day price.
1 | e.g.: |
( 2 ). If the profit < 0. Choose a new day to buy.
1 | e.g.: |
Code
1 | int maxProfit = 0; |
It is also called Kadane’s Algorithm.