LeetCode 121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
簡(jiǎn)單粗暴的第一種解法:
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;} };第二種解法:
從最后一個(gè)元素開始遍歷(vector不能為空),維持一個(gè)最大價(jià)格和一個(gè)最大收益
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;} };?
總結(jié)
以上是生活随笔為你收集整理的LeetCode 121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SpringBoot + Spring
- 下一篇: 万字长文精华之数据中台构建五步法