LeetCode 121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡單粗暴的第一種解法:
class Solution { public:int maxProfit(vector<int>& prices) {int m = prices.size();int maxprofit = 0;for (int k = 0; k < m; k++){for (int i = k; i < m; i++){if (prices[i] - prices[k] > maxprofit)maxprofit = prices[i] - prices[k];}}return maxprofit;} };第二種解法:
從最后一個元素開始遍歷(vector不能為空),維持一個最大價格和一個最大收益
class Solution { public:int maxProfit(vector<int>& prices) {int m = prices.size();if (m == 0) return 0;int maxprofit = 0;int maxprice = prices.back();for (int k = m-1; k >= 0; k--){if (prices[k] > maxprice) maxprice = prices[k];else if(maxprice - prices[k] > maxprofit) maxprofit = maxprice - prices[k];}return maxprofit;} };?
總結
以上是生活随笔為你收集整理的LeetCode 121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot + Spring
- 下一篇: 万字长文精华之数据中台构建五步法