当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
Apache DolphinScheduler's new generation of distributed workflow task scheduling platform in practice - Part 1
HCIP - MPLS VPN experiment
One article to understand twenty kinds of switching power supply topologies
How to implement Golang DES encryption and decryption?
Devops和低代码的故事:螳螂捕蝉,黄雀在后
树莓派_烧写Raspberry官方镜像系统
怎么在本地电脑上运行dist文件
浅论各种调试接口(JTAG、SWD、RDI、Jlink、Ulink、STlink)的区别
一个低级错误导致的诡异现象——走近科学能拍三集,(C语言)最简单的数组元素读取,不正确!?
【 HMS core 】 【 】 the FAQ HMS Toolkit collection of typical questions 1
随机推荐
宝塔搭建DM企业建站系统源码实测
无法定位程序输入点ucrtbase.abort于动态链接库api-ms-win-crt-runtime-|1-1-0.dll上
Functional Interfaces & Lambda Expressions - Simple Application Notes
延迟队列MQ
20220728使用电脑上的蓝牙和汇承科技的蓝牙模块HC-05配对蓝牙串口传输
Use the R language to read the csv file into a data frame, and then view the properties of each column.
Only after such a stage of development can digital retail have a new evolution
Unity performance analysis Unity Profile performance analysis tool
研发人员的悲剧——“庞氏骗局”
电路分析:运放和三极管组成的恒流源电路
ACL 2022 | Introduce angular margin to construct comparative learning objectives and enhance text semantic discrimination ability
How to use Jmeter to carry out high concurrency in scenarios such as panic buying and seckill?
Scala
企业数字化建设,自研还是采购?
EMC过不了?都是PCB工程师的锅?
电源完整性的去耦和层间耦合电容
Jetpack Compose 从入门到入门(八)
Detailed description of iperf3 parameter options
功能测试、UI自动化测试(web自动化测试)、接口自动化测试
Concise Notes on Integrals - Types of Curve Integrals of the First Kind