算法題--最佳股票交易策略II

image.png

0. 鏈接

題目鏈接

1. 題目

Say you have an array prices 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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Constraints:

1 <= prices.length <= 3 * 10 ^ 4
0 <= prices[i] <= 10 ^ 4

2. 思路1: 遍歷找波峰波谷

  • 記錄buy_price, sell_price, max_profit
  • 從左到右遍歷,
    • 遇到price比buy_price小的, 則更新buy_price, - 遇到price比sell_price大的, 則更新sell_price
    • 當(dāng)遇到price比上一個(gè)sell_price小, 說(shuō)明上一個(gè)sell_price就是波峰, 此時(shí)進(jìn)行一次結(jié)算 max_profit += sell_price - buy_price, 并重置buy_price=price, sell_price=None
  • 時(shí)間復(fù)雜度: ```O(N)``
  • 空間復(fù)雜度: O(1)

3. 代碼

# coding:utf8
from typing import List


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) == 0:
            return 0

        buy_price = prices[0]
        sell_price = None
        max_profit = 0
        for i in range(1, len(prices)):
            price = prices[i]
            if sell_price is None:
                if price < buy_price:
                    buy_price = price
                else:
                    sell_price = price
            else:
                if price < sell_price:
                    max_profit += sell_price - buy_price
                    buy_price = price
                    sell_price = None
                else:
                    sell_price = price
        if sell_price is not None:
            max_profit += sell_price - buy_price

        return max_profit


def my_test(solution, prices):
    print('input: {}; output: {}'.format(prices, solution.maxProfit(prices)))


solution = Solution()
my_test(solution, [7, 1, 5, 3, 6, 4])
my_test(solution, [1, 2, 3, 4, 5])
my_test(solution, [7, 6, 4, 3, 1])


輸出結(jié)果

input: [7, 1, 5, 3, 6, 4]; output: 7
input: [1, 2, 3, 4, 5]; output: 4
input: [7, 6, 4, 3, 1]; output: 0

4. 結(jié)果

image.png

5. 思路2: 積分法

  • 求所有呈上升趨勢(shì)的階段的增量和
  • 時(shí)間復(fù)雜度 O(N)
  • 空間復(fù)雜度 O(1)

6. 代碼

# coding:utf8
from typing import List


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        max_profit = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i - 1]:
                max_profit += prices[i] - prices[i - 1]
        return max_profit


def my_test(solution, prices):
    print('input: {}; output: {}'.format(prices, solution.maxProfit(prices)))


solution = Solution()
my_test(solution, [7, 1, 5, 3, 6, 4])
my_test(solution, [1, 2, 3, 4, 5])
my_test(solution, [7, 6, 4, 3, 1])

輸出結(jié)果為

input: [7, 1, 5, 3, 6, 4]; output: 7
input: [1, 2, 3, 4, 5]; output: 4
input: [7, 6, 4, 3, 1]; output: 0

7. 結(jié)果

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末搁料,一起剝皮案震驚了整個(gè)濱河市或详,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌郭计,老刑警劉巖鸭叙,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異拣宏,居然都是意外死亡沈贝,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)勋乾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)宋下,“玉大人,你說(shuō)我怎么就攤上這事辑莫⊙纾” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵各吨,是天一觀的道長(zhǎng)枝笨。 經(jīng)常有香客問(wèn)我,道長(zhǎng)揭蜒,這世上最難降的妖魔是什么横浑? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮屉更,結(jié)果婚禮上徙融,老公的妹妹穿的比我還像新娘。我一直安慰自己瑰谜,他們只是感情好欺冀,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布树绩。 她就那樣靜靜地躺著,像睡著了一般隐轩。 火紅的嫁衣襯著肌膚如雪饺饭。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,598評(píng)論 1 305
  • 那天职车,我揣著相機(jī)與錄音砰奕,去河邊找鬼。 笑死提鸟,一個(gè)胖子當(dāng)著我的面吹牛军援,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播称勋,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼胸哥,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了赡鲜?” 一聲冷哼從身側(cè)響起空厌,我...
    開(kāi)封第一講書(shū)人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎银酬,沒(méi)想到半個(gè)月后嘲更,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡揩瞪,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年赋朦,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片李破。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡宠哄,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出嗤攻,到底是詐尸還是另有隱情毛嫉,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布妇菱,位于F島的核電站承粤,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏闯团。R本人自食惡果不足惜辛臊,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望偷俭。 院中可真熱鬧浪讳,春花似錦缰盏、人聲如沸涌萤。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)负溪。三九已至透揣,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間川抡,已是汗流浹背辐真。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留崖堤,地道東北人侍咱。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像密幔,于是被迫代替她去往敵國(guó)和親楔脯。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355