当前位置:网站首页>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;
}
}
边栏推荐
- 【 HMS core 】 【 】 the FAQ HMS Toolkit collection of typical questions 1
- 2022/07/29 学习笔记 (day19)异常处理
- PyQt5快速开发与实战 7.4 事件处理机制入门 and 7.5 窗口数据传递
- Excel xlsx file not supported两种解决办法【杭州多测师】【杭州多测师_王sir】
- Integral Topic Notes - Path Independent Conditions
- 仿牛客网项目第二章:开发社区登录模块(详细步骤和思路)
- 图像分析:投影曲线的波峰查找
- 百度paddleocr检测训练
- 2022杭电多校第一场
- Use the R language to read the csv file into a data frame, and then view the properties of each column.
猜你喜欢
随机推荐
瑞吉外卖项目(五) 菜品管理业务开发
Access to display the data
积分简明笔记-第二类曲线积分的类型
Is R&D moving to FAE (Field Application Engineer), is it moving away from technology?Is there a future?
Leetcode - 990: equations of satisfiability
The sword refers to offer 48: the longest non-repeating substring
342 · 山谷序列
虚幻引擎图文笔记:could not be compiled. Try rebuilding from source manually.问题的解决
研发转至FAE(现场应用工程师),是否远离技术了?有前途吗?
How to run dist file on local computer
宝塔搭建DM企业建站系统源码实测
How to Assemble a Registry
转行软件测试,报培训班3个月出来就是高薪工作,靠谱吗?
【愚公系列】2022年07月 Go教学课程 021-Go容器之切片操作
经历了这样一个阶段的发展之后,数字零售才能有新的进化
如何使用 Jmeter 进行抢购、秒杀等场景下,进行高并发?
MySQL Explain 使用及参数详解
How to use Jmeter to carry out high concurrency in scenarios such as panic buying and seckill?
积分专题笔记-曲线面积分三大公式
PyQt5快速开发与实战 8.1 窗口风格









