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)
阅读原文可进入题目
- Gridview行上下移动自己做的一个小例子(第一种方法)
- Hadoop伪分布式集群安装部署
- sql 表有没有自增列,插入自增列值
- jsp中的JSTL与EL表达式用法及区别(二)
- WPF 给控件添加复制事作
- wpf RoutedUICommand 绑定
- jsp中的JSTL与EL表达式用法及区别(一)
- java线程池模型
- lock小记
- HTML布局的基本要点
- Building a Middle Tier Component using NHibernate and Spring.NET
- Linq 和DefaultView两种方法去掉DataTable 里的重复行
- MySQL事务autocommit自动提交
- wcf webHttpBinding Post 大数据量提交 ios c#客户端
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法