- leetcode:121. Best Time to Buy a
- 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
- 每天(?)一道LeetCode(14) Best Time to
- Leetcode 股票合集 【121、122、714、309】
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
解法:
class Solution {
public int maxProfit(int[] prices) {
if(prices.length < 2){
return 0;
}
int maxprofit = 0;
int minprice = prices[0];
int temp;
for(int ele: prices){
temp = ele - minprice;
if(temp > maxprofit){
maxprofit = temp;
}
if(ele < minprice){
minprice = ele;
}
}
return maxprofit;
}
}
第一次做觉得理所当然的方法第二次居然不敢确定这样的做法是不是准确:
有两点值得指出的是:
- maxprofit可以将目前最好的结果保留下来
- 碰到当前price低于minprice的时候敢直接将minprice替换为当前price的理由为:
- 被替换掉的minprice的最优解如果存在则已经被存储在maxprofit中
- 假如最适合被替换的minprice的卖出价在后面且当前price低于minprice,则当前价格做买入价会有更高的profit
网友评论