[LeetCode By Go 38]Add to List 122. Best Time to Buy and Sell Stock II

題目

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).

題目大意

假設(shè)有一個(gè)數(shù)組,它的第i個(gè)元素是一個(gè)給定的股票在第i天的價(jià)格。設(shè)計(jì)一個(gè)算法來找到最大的利潤。你可以完成盡可能多的交易(多次買賣股票)。然而,你不能同時(shí)參與多個(gè)交易(你必須在再次購買前出售股票)。
給出一個(gè)數(shù)組樣例[2,1,2,0,1], 返回 2

解題思路

本題由于是可以操作任意次數(shù),只為獲得最大收益,而且對于一個(gè)上升子序列,比如:[5, 1, 2, 3, 4]中的1, 2, 3, 4序列來說,對于兩種操作方案:
1 在1買入,4賣出
2 在1買入,2賣出同時(shí)買入,3賣出同時(shí)買入,4賣出
這兩種操作下,收益是一樣的。
所以可以從頭到尾掃描prices,如果price[i] – price[i-1]大于零則計(jì)入最后的收益中。即貪心法

代碼

func maxProfit(prices []int) int {
    len1 := len(prices)

    var sum int

    for i := 1; i < len1; i++{
        if prices[i] > prices[i-1] {
            sum += prices[i] - prices[i-1]
        }

    }

    return sum
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容