- 【2019-07-30】leetcode(121-130)
- leetcode:121. Best Time to Buy a
- 121. Best Time to Buy and Sell S
- LeetCode #121 #122 #123 #188 #30
- #121. Best Time to Buy and Sell
- [LeetCode] 121. Best Time to Buy
- Leetcode121 - 123 (dp problems)
- [数组]121. Best Time to Buy and Se
- 121. Best Time to Buy and Sell S
- Leetcode121-Best Time to Buy and
Find the range of the stock price which follow the time order
Example 1:
Input: [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.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Solution
Time O(N)
Space O(1)
难点是峰值有可能会对其造成干扰,可能开始出现的max峰值并不能达到profit最大值,找最后出现的最小值可能也不能。因此在one pass的时候可以一边记录当前最小,一边纪录profit,因为在找peak的时候min越小越好。
方法即使用One-pass的方式,始终记录当前遇到的最小值
class Solution {
public int maxProfit(int[] prices) {
int min,profit,max_profit;
min=Integer.MAX_VALUE;
max_profit=0;
for(int i=0;i<prices.length;i++){
if(prices[i]<min){
min=prices[i]; // guarantee the smallest val which own the order
}
else{
profit=prices[i]-min;
if(max_profit<profit)
max_profit=profit;
}
}
return max_profit;
}
}```
网友评论