每日刷题---买卖股票的最佳时机 II

105 阅读1分钟

买卖股票的最佳时机 II

给定一个数组 prices ,其中 prices[i] 表示股票第 i 天的价格。

在每一天,你可能会决定购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以购买它,然后在 同一天 出售。 返回 你能获得的 最大 利润 。

1、贪心算法 那么这道题使用贪心算法也是最容易解决的,只要是上涨的我们就要计算他们的差值进行累加,不需要再找开始上涨的最小值和最大值。我举个例子。 比如a<b<c<d,因为从a到d一直是上涨的,那么最大值和最小值的差值就是d-a,也可以写成(b-a)+(c-b)+(d-c),搞懂了这个公式所有的一切都明白了。如果还不明白,可以想象成数组中前一个值减去后一个值,构成一个新的数组,我们只需要计算这个新数组中正数的和即可,这里以示例1为例画个图看下


    if prices.isEmpty {

        return 0

    }

    var total = 0

    for index in 0..<prices.count - 1 {

        total = max(prices[index + 1] - prices[index], 0) + total

    }

    return total

}

2、### 动态规划

func maxProfit(_ prices: [Int]) -> Int {

    if prices.isEmpty {

        return 0

    }

    if prices.count < 2 {

        return  0

    }
    var hold = -prices[0]

    var noHold = 0

    for price in 1..<prices.count {

        noHold = max(noHold, hold + prices[price])

        hold = max(hold, noHold - prices[price])

    }

    return noHold

}