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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

leetcode笔记(一)309. Best Time to Buy and Sell Stock with Cooldown

發(fā)布時(shí)間:2025/5/22 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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]
  • 解題思路 (原思路鏈接)
這道題目自己一開(kāi)始根本沒(méi)有想到用動(dòng)態(tài)規(guī)劃,菜鳥(niǎo)本色。之后看了dicussion區(qū)域排名第一的答案,也是云里霧里。
還好碰到了這個(gè)解決思路。這個(gè)方案把每天分為四個(gè)狀態(tài)
  • 有股票,賣(mài) = 前天(有股票,休息)+ price 或者 前天(沒(méi)股票,買(mǎi))+ price
  • 有股票,休息 = 前天(有股票,休息)或者 前天(沒(méi)股票,買(mǎi))
  • 沒(méi)股票,買(mǎi) = 前天(沒(méi)股票,休息)- price ==》 冷卻期所以不可能是 有股票,賣(mài)
  • 沒(méi)股票,休息 = 前天(沒(méi)股票,休息)或者 前天(有股票,賣(mà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)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。