国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode 122. Best Time to Buy and Sell Stock II

2019-11-14 09:44:15
字體:
來源:轉載
供稿:網友

Say you have an array for which the ith element is the PRice of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

s思路: 1. 和 Leetcode 121. Best Time to Buy and Sell Stock不一樣,前一道題要求只能最多買賣一次找最大profit;這道題要求可以多次交易。 2. 初看道題,有點覺得下不了手,想到在121題一次交易時需要兩個變量lowprice和profit,那么多次交易不得需要多個變量啊??其實,多次反而不用這些求最小值的過程,遍歷一遍,遇到比lowprice大的就直接把差值加在profit上,然后把lowprice更新成這個值,繼續找,再次遇到比現在lowprice大的,繼續把差值加在profit上,然后把這個值賦給lowprice。可以看出,只要有利可圖(后面值比前面大),就reap it。然后更新lowprice。 3. 這種有很強方向性的題目,即:后面的數大于前面的數,而遍歷又是從左往右。一般有o(n) 4. 方法2參考了之前做的,就是遍歷一遍,比較前后兩個數的大小,如果當前數比前一個數大,則把差值加在profit。不用計算lowprice.這才是終極的解法!因為要求不是一次、也不是兩次交易,要求無限次交易,所以就沒有必要找最小值了,反而簡單!

//方法1:和方法2比,有些復雜,但物理意義清楚class Solution {public: int maxProfit(vector<int>& prices) { // int lowprice=INT_MAX; int profit=0; for(int i=0;i<prices.size();i++){ lowprice=min(lowprice,prices[i]); if(prices[i]>lowprice){ profit+=prices[i]-lowprice; lowprice=prices[i]; } } return profit; }};//方法2:簡潔class Solution {public: int maxProfit(vector<int>& prices) { // int profit=0; for(int i=1;i<prices.size();i++){ if(prices[i]>prices[i-1]) prifit+=prices[i]-prices[i-1]; } return profit; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 门头沟区| 建瓯市| 同江市| 望奎县| 卢龙县| 江安县| 玉田县| 玉树县| 大同县| 香河县| 和林格尔县| 高要市| 马山县| 利津县| 汪清县| 临沂市| 龙井市| 怀安县| 杂多县| 浮山县| 乐至县| 扶绥县| 和林格尔县| 灵山县| 子洲县| 永康市| 定安县| 丽江市| 洪洞县| 潜江市| 贺州市| 蒙自县| 长顺县| 叶城县| 晋中市| 灵台县| 百色市| 永年县| 红安县| 额尔古纳市| 乌兰县|