leetcode笔记(一)309. Best Time to Buy and Sell Stock with Cooldown
生活随笔
收集整理的這篇文章主要介紹了
leetcode笔记(一)309. Best Time to Buy and Sell Stock with Cooldown
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
- 題目描述 (原題目鏈接)
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) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2] maxProfit = 3 transactions = [buy, sell, cooldown, buy, sell]- 解題思路 (原思路鏈接)
還好碰到了這個(gè)解決思路。這個(gè)方案把每天分為四個(gè)狀態(tài)
結(jié)合這個(gè)思路,編碼實(shí)現(xiàn)如下:
需要額外注意的一點(diǎn)是第0天的初始化,(有股票,休息)= -price 因?yàn)橄乱惶炜赡苜u(mài)這個(gè)股票,所以計(jì)價(jià)時(shí)相當(dāng)于第0天買(mǎi)了。
int maxProfit(vector<int>& prices) {int has_sell, has_sell_before;int has_rest, has_rest_before;int no_buy, no_buy_before;int no_rest, no_rest_before;int size = prices.size();if(size < 2)return 0;has_sell_before = 0;has_rest_before = -prices[0];no_buy_before = -prices[0];no_rest_before = 0;for(int i = 1; i < size; i++){has_sell = max(has_rest_before + prices[i], no_buy_before + prices[i]);has_rest = max(has_rest_before, no_buy_before);no_buy = no_rest_before - prices[i];no_rest = max(no_rest_before, has_sell_before);has_sell_before = has_sell;has_rest_before = has_rest;no_buy_before = no_buy;no_rest_before = no_rest;}// find the max between has_sell and no_restreturn max(has_sell, no_rest);}?
轉(zhuǎn)載于:https://www.cnblogs.com/niuxu18/p/note_leetcode_1.html
總結(jié)
以上是生活随笔為你收集整理的leetcode笔记(一)309. Best Time to Buy and Sell Stock with Cooldown的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 车险到期了晚点买行吗
- 下一篇: springboot 自动配置