当前位置:网站首页>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;
}
}
边栏推荐
- Kotlin 值类 - value class
- Google Cloud Spanner的实践经验
- C language classic practice questions (3) - "Hanoi Tower (Hanoi)"
- sort函数使用cmp出错Line 22: Char 38: error: reference to non-static member function must be called
- iperf3 参数选项详细说明
- MySQL Explain 使用及参数详解
- 【零基础玩转BLDC系列】以GD32F30x为例定时器相关功能详解
- 负电压电路(原理分析)
- 树莓派_烧写Raspberry官方镜像系统
- 功能测试、UI自动化测试(web自动化测试)、接口自动化测试
猜你喜欢

积分简明笔记-第二类曲线积分的类型

Excel xlsx file not supported两种解决办法【杭州多测师】【杭州多测师_王sir】

虚幻引擎图文笔记:could not be compiled. Try rebuilding from source manually.问题的解决

百度paddleocr检测训练

MySQL数据库题库

The difference between DDR, GDDR, QDR

九九乘法表

【零基础玩转BLDC系列】以GD32F30x为例定时器相关功能详解

MySQL Explain usage and parameter detailed explanation

20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
随机推荐
读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》
Apache DolphinScheduler's new generation of distributed workflow task scheduling platform in practice - Part 1
统一异常处理导致ResponseBodyAdvice失效
网络/信息安全顶刊及相关期刊会议
The difference between DDR, GDDR, QDR
开关电源波纹的产生、测量及抑制,一篇全搞定!
0729放假自习
PyQt5快速开发与实战 8.1 窗口风格
How to run dist file on local computer
20个电路能懂5个以上,足以证明你在电子行业混过!
An article to understand service governance in distributed development
How to avoid CMDB becoming a data island?
C语言经典练习题(3)——“汉诺塔(Hanoi)“
Activating data potential Amazon cloud technology reshapes cloud storage "family bucket"
TreeSet解析
20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
获取显示器数据
Apache DolphinScheduler新一代分布式工作流任务调度平台实战-上
涛思 TDengine 2.6+优化参数
2022 Hangzhou Electric Multi-School 2nd Game