摘要:題目鏈接來解,要用兩個(gè)分別表示現(xiàn)在的操作是還是,優(yōu)化空間用滾動(dòng)數(shù)組,或者幾個(gè)
309. Best Time to Buy and Sell Stock with Cooldown
題目鏈接:https://leetcode.com/problems...
dp來解,要用兩個(gè)dp array分別表示現(xiàn)在的操作是buy還是sell,優(yōu)化空間用滾動(dòng)數(shù)組,或者幾個(gè)int
public class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) return 0; /* buy[i] = Math.max(sell[i-2]-prices[i], buy[i-1]) * sell[i] = Math.max(sell[i-1], buy[i-1] + prices[i]) */ int preBuy = Integer.MIN_VALUE, curBuy = Integer.MIN_VALUE; int preSell = 0, curSell = 0; for(int price : prices) { preBuy = curBuy; curBuy = Math.max(preSell - price, preBuy); preSell = curSell; curSell = Math.max(preSell, preBuy + price); } return curSell; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/66666.html
摘要:示例輸入輸出解釋對(duì)應(yīng)的交易狀態(tài)為買入賣出冷凍期買入賣出思路這道題使用動(dòng)態(tài)規(guī)劃。狀態(tài)表示當(dāng)天休息能夠獲得的最大價(jià)值,表示當(dāng)天持有股票能夠獲得的最大價(jià)值,表示當(dāng)天持有股票能夠獲得的最大價(jià)值。 Description Say you have an array for which the ith element is the price of a given stock on day i. ...
摘要:分析因?yàn)楫?dāng)前日期買賣股票會(huì)受到之前日期買賣股票行為的影響,首先考慮到用解決。所以我們可以用兩個(gè)數(shù)組分別記錄當(dāng)前持股跟未持股的狀態(tài)。 Best Time to Buy and Sell Stock with Cooldown Say you have an array for which the ith element is the price of a given stock on ...
121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a given stock on day i.If you were only permitted to complete at most one transaction (i.e., buy on...
摘要:關(guān)鍵字,,算法,,動(dòng)態(tài)規(guī)劃,上關(guān)于主題的題目有四個(gè)這四個(gè)題目難度依次遞增。其中第四個(gè)問題是尋求一個(gè)通解,在給定和最大買賣次數(shù)的情況下,求最大收益。首先大致的解題方向是動(dòng)態(tài)規(guī)劃,這個(gè)應(yīng)該不難想到。之后就是怎么找到狀態(tài),怎么列狀態(tài)轉(zhuǎn)移方程。 關(guān)鍵字:leetcode,Best Time To Buy And Sell Stock,算法,algorithm,動(dòng)態(tài)規(guī)劃,dynamic prog...
摘要:求可能的最大利潤題目給了兩個(gè)例子最大利潤就是進(jìn)價(jià)為,賣價(jià)為的時(shí)候,利潤為在這個(gè)案例中,進(jìn)價(jià)一直高于售價(jià),所以無法成交,返回。主要注意一下,先買入才能賣出賣價(jià)一定要比買入價(jià)格高才能成交就可以了。 題目詳情 Say you have an array for which the ith element is the price of a given stock on day i.If yo...
閱讀 2159·2021-11-22 15:22
閱讀 1299·2021-11-11 16:54
閱讀 1830·2021-09-23 11:32
閱讀 3021·2021-09-22 10:02
閱讀 1782·2019-08-30 12:59
閱讀 1096·2019-08-29 16:27
閱讀 631·2019-08-29 13:21
閱讀 2470·2019-08-28 17:57