Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock II
Posted xpp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock II相关的知识,希望对你有一定的参考价值。
方法:记录便利过程中的best profit
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() < 2) return 0; int profit = 0, minValue = prices[0]; for(int i=0; i<prices.size(); ++i) { profit = max(profit, prices[i] - minValue); if(prices[i] < minValue) minValue = prices[i]; } return profit; } };
Best Time to Buy and Sell Stock II
class Solution { public: int maxProfit(vector<int>& prices) { int sum = 0; for(int i=1; i<prices.size(); ++i) { if(prices[i] - prices[i-1] > 0) sum += prices[i] - prices[i-1]; } return sum; } };
以上是关于Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock II的主要内容,如果未能解决你的问题,请参考以下文章
最强解析面试题:best-time-to-buy-and-sell-stock
最强解析面试题:best-time-to-buy-and-sell-stock
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II