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)
阅读原文可进入题目
- Java中使用Hibernate系列之单向Set-based的关联学习(第四节)
- Java中使用Hibernate系列之加载并存储对象学习(第三节)
- Java中使用Hibernate系列之启动方法学习(第二节)
- Java中使用Hibernate系列之映射文件学习(第一节)
- Java中为图片添加水印效果的方法——实例代码
- Java中使用Hibernate系列之过滤器(filters)学习
- Node.js中的内存泄漏分析
- Java实现把整数转换为英语单词的方法,实用代码
- Chrome XSS审计之SVG标签绕过
- Java实现的一个简单计算器,有字符分析功能
- Java中实现判断括号是否有效的方法,实用代码
- Java中使用栈实现一个队列,实用代码
- NDK 的开发流程
- 蜜罐背后的影子系统探秘
- 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 数组属性和方法
- ubuntu14.04安装jdk1.8的教程
- Linux nohup实现后台运行程序及查看(nohup与&)
- 详解Linux 服务管理两种方式service和systemctl
- CentOS6.5安装python3.7详细步骤
- Centos7.5配置IP地址的实现
- linux里daily_routine实例代码详解
- 类Linux环境安装jdk1.8及环境变量配置详解
- CentOS7yum安装PHP7.2的操作方法
- CentOS 7中 Apache Web 服务器安装配置教程
- Win10安装Linux系统的教程图解
- 浅谈ubuntu执行.sh文件几种方式区别
- CentOS7使用yum安装PostgreSQL和PostGIS的方法
- Linux Windows下设置定时执行任务的方法
- 详解ssh免密码登录配置方法(图示加命令)
- centos 7 修改sshd | 禁止 root登录及sshd端口脚本定义