日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode+51nod】股票低买高卖N题

發布時間:2025/3/15 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode+51nod】股票低买高卖N题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

【121】Best Time to Buy and Sell Stock (2018年11月25日重新復習)

給一個數組代表股票每天的價格,只能有一次交易,即一次買入一次賣出,求最大收益。

題解:用一個變量維護此時的最大收益和最小成本。遍歷數組求值。

1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 int minPrice = INT_MAX; 5 int maxProfit = 0; 6 for (auto ele : prices) { 7 minPrice = min(ele, minPrice); 8 maxProfit = max(maxProfit, (ele - minPrice)); 9 } 10 return maxProfit; 11 } 12 }; View Code

?2018年11月25日,這次一次 AC 了。

1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 const int n = prices.size(); 5 if (n < 2) {return 0;} 6 int buy = prices[0], sell = 0; 7 int ret = 0; 8 for (int i = 1; i < n; ++i) { 9 sell = prices[i]; 10 if (buy < sell) { 11 ret = max(sell - buy, ret); 12 } else { 13 buy = prices[i]; 14 } 15 } 16 return ret; 17 } 18 }; View Code

?

【122】 Best Time to Buy and Sell Stock II (2018年11月25日復習)

這題是給了一個數組代表股票每天的價格,可以做任意次的交易,但是不能同時持有多支股票。(每次的操作方式只能是先買,然后賣了,再買。不能在賣了之前再次買入。)

題解:這題我是用了貪心,每次發現今天的價格比昨天的價格高,就在昨天買入,今天賣出。

1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 const int n = prices.size(); 5 int ret = 0; 6 for (int i = 1; i < n; ++i) { 7 if (prices[i] - prices[i-1] > 0) { 8 ret += prices[i] - prices[i-1]; 9 } 10 } 11 return ret; 12 } 13 }; View Code

還可以用dp解答,dp通用一些。以后那些變種都是dp的變種。

?

【123】Best Time to Buy and Sell Stock III (2018年11月30日,復習)

給了一個數組代表每天股票的價格,只能做兩次交易,問最大的盈利是多少。(還跟原來的條件是一樣的,不支持同時持有多股票,每次操作方式都是先買,賣了,然后才能再買。)

題解:這題我用了類似動態規劃這種做法,狀態其實很簡單,四個狀態,分別代表第一次買入后的錢,第一次賣出后的錢,第二次買入后的錢,第二次賣出后的錢。最后這四個數可能都是負數,這個時候不買最好了。?

1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 const int n = prices.size(); 5 if (n == 0) {return 0;} 6 vector<int> g(4, INT_MIN); 7 g[0] = -prices[0]; 8 for (int i = 1; i < n; ++i) { 9 g[0] = max(g[0], -prices[i]); 10 g[1] = max(g[1], g[0]+prices[i]); 11 g[2] = max(g[2], g[1]-prices[i]); 12 g[3] = max(g[3], g[2]+prices[i]); 13 } 14 return max(0, max(g[1], g[3])); 15 } 16 }; View Code

?

?

【188】 Best Time to Buy and Sell Stock IV

?

【309】 Best Time to Buy and Sell Stock with Cooldown

?

【714】 Best Time to Buy and Sell Stock with Transaction Fee

?

轉載于:https://www.cnblogs.com/zhangwanying/p/9360841.html

總結

以上是生活随笔為你收集整理的【LeetCode+51nod】股票低买高卖N题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。