当前位置:网站首页>leetcode 剑指 Offer 63. 股票的最大利润
leetcode 剑指 Offer 63. 股票的最大利润
2022-07-30 08:52:00 【kt1776133839】
题目描述:
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
样例:
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
限制:
0 <= 数组长度 <= 10^5
解题思路:
设共有 n 天,第 a 天买,第 b天卖,则需保证 a<b ;可推出交易方案数共有:
(n−1)+(n−2)+⋯+2+1=n(n−1)/2
因此,暴力法的时间复杂度为 O(n2) 。考虑使用动态规划降低时间复杂度,以下按照流程解题。
动态规划
状态定义: 设动态规划列表 dp ,dp[i] 代表以 prices[i] 为结尾的子数组的最大利润(以下简称为 前 i日的最大利润 )。
转移方程: 由于题目限定 “买卖该股票一次” ,因此前 i 日最大利润 dp[i] 等于前 i−1 日最大利润 dp[i−1]和第 i 日卖出的最大利润中的最大值。
前i日最大利润=max(前(i−1)日最大利润,第i日价格−前i日最低价格)
dp[i]=max(dp[i−1],prices[i]−min(prices[0:i]))
初始状态: dp[0]=0dp[0] = 0dp[0]=0 ,即首日利润为 000 ;
返回值: dp[n−1]dp[n - 1]dp[n−1] ,其中 nnn 为 dpdpdp 列表长度。
Java程序:
class Solution {
public int maxProfit(int[] prices) {
int cost = Integer.MAX_VALUE, profit = 0;
for(int price : prices) {
cost = Math.min(cost, price);
profit = Math.max(profit, price - cost);
}
return profit;
}
}
边栏推荐
- [Yugong Series] July 2022 Go Teaching Course 021-Slicing Operation of Go Containers
- The difference between DDR, GDDR, QDR
- 仿牛客网项目第二章:开发社区登录模块(详细步骤和思路)
- 一文理解分布式开发中的服务治理
- Unity performance analysis Unity Profile performance analysis tool
- 342 · 山谷序列
- EMC过不了?都是PCB工程师的锅?
- 电路分析:运放和三极管组成的恒流源电路
- 用示波器揭示以太网传输机制
- 20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
猜你喜欢
[Yugong Series] July 2022 Go Teaching Course 021-Slicing Operation of Go Containers
How to Assemble a Registry
C language classic practice questions (3) - "Hanoi Tower (Hanoi)"
Kotlin value class - value class
Circuit analysis: constant current source circuit composed of op amp and triode
It is said that FPGA is high-end, what can it do?
Explain the problem of change exchange in simple terms - the shell of the backpack problem
嘉为鲸翼·多云管理平台荣获信通院可信云技术服务最佳实践
图像分析:投影曲线的波峰查找
2022杭电多校第二场
随机推荐
剑指offer 48:最长不重复子串
How to Assemble a Registry
积分简明笔记-第二类曲线积分的类型
Leetcode - 990: equations of satisfiability
网络/信息安全顶刊及相关期刊会议
函数式接口&Lambda表达式——简单应用笔记
Google Cloud Spanner的实践经验
0729放假自习
Kotlin 值类 - value class
嘉为鲸翼·多云管理平台荣获信通院可信云技术服务最佳实践
2022/07/29 学习笔记 (day19)异常处理
一文理解分布式开发中的服务治理
69. Sqrt(x)x 的平方根
Apache DolphinScheduler新一代分布式工作流任务调度平台实战-上
One article to understand twenty kinds of switching power supply topologies
Explain the problem of change exchange in simple terms - the shell of the backpack problem
js currying
宝塔搭建DM企业建站系统源码实测
读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》
C# 之 $ – 字符串内插