leetcode: explore-array-22 买卖股票的最佳时机 II

时间:2022-07-23
本文章向大家介绍leetcode: explore-array-22 买卖股票的最佳时机 II,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

leetcode explore 初级算法第二题:买卖股票的最佳时机 II。这个系列目前一共有5道题目:

买卖股票的最佳时机 I:简单 买卖股票的最佳时机 II:简单 买卖股票的最佳时机 III:困难 买卖股票的最佳时机 IV:困难 最佳买卖股票时机含冷冻期:中等

因为我们遇到这个题目的时候是 II,所以这里我们解决 I 和 II。

个人在做的时候觉得 II 要比 I 简单,所以我们先来看 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 (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.

同样我们先来分析题目意思:

1、输入:一个数组,只包含数字,每个数字表示当前股票的价格 2、输出:一个数字,多次交易可获得的最大利润 3、注意:只允许一次买入一次买出,即当你买入后,不同再次买入,必须卖出后才可以买入;同一个位置的股票可以多次买入卖出;位置也可以理解为某个日期的股票,错过时间后不能再次进行交易

参考答案

其实这个题目最好帮助找到答案的办法是画一个折线图,我们以题目中给的例子 [7,1,5,3,6,4] 为例,折线图如下所示:

我们很容易发现,想得到整个周期间内可获得的最大利润,即将所有递增的区间相加,因为递增区域即代表我们获得了利润,显然只要是有利润就获得,最终的利润才是最高的。

参考代码如下:

from typing import List

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

        total = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                total += prices[i] - prices[i-1]

        return total


if __name__ == "__main__":
    s = Solution()
    print(s.maxProfit([7, 1, 5, 3, 6, 4]))

好了,说完第 II 题,我们再回过头来看看第 I 题。

I 题

看下题目:

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:

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

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

题目大意和 II 题差不多,只是最终求最大利润的方式不同。同样我们来拆解下题目:

1、输入:一个数组,只包含数字,数字代表当天股票的价格 2、输出:一个数字,代表整个股票周期,一次交易可获得的最大利润 3、注意:只允许一次交易,即一次买入,一次买出

I 题参考答案

这个题目看上去是比第 II 题要好理解,但做起来实际上没有第 I 题好实现,最暴力的解法即是循环两次,找到每种情况的利润,然后取最大值,但这样O(n^2)的时间复杂度显然不是很好的方式,当然提交也会超过时间限制。

思路有很多种,关键还是找到递增区间,找到递增区间最大的即是我们要找的答案。参考答案如下:

from typing import List


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

        min_num = None          # 当前递增区域的最小值
        max_sum = 0             # 最大利润值
        for i in range(1, len(prices)):
            tmp = prices[i] - prices[i-1]
            if tmp <= 0:
                continue
            if min_num is None or prices[i - 1] < min_num:
                min_num = prices[i - 1]
            tmp_sum = prices[i] - min_num
            if tmp_sum > max_sum:
                max_sum = tmp_sum

        return max_sum


if __name__ == "__main__":
    s = Solution()
    print(s.maxProfit([7, 1, 5, 3, 6, 4]))
    print(s.maxProfit([7, 6, 4, 3, 1]))
    print(s.maxProfit([3, 3, 5, 0, 0, 3, 1, 4]))
    print(s.maxProfit([1, 2, 4]))

这样的时间复杂度为 O(n)

阅读原文可进入题目