当前位置:网站首页>Maximum profit of stock (offer 63)
Maximum profit of stock (offer 63)
2022-06-27 14:22:00 【input_ out】
The biggest profit of stocks ( The finger of the sword Offer 63)
1 Title Description
Suppose you store the price of a stock in an array in chronological order , What's the maximum profit you can get from buying and selling this stock at one time ?
Input : [7,1,5,3,6,4]
Output : 5
explain : In the 2 God ( Stock price = 1) Buy when , In the 5 God ( Stock price = 6) Sell when ,
Maximum profit = 6-1 = 5 Note that profit cannot be 7-1 = 6, Because the selling price needs to be higher than the buying price .
2 Thought analysis
Using the violence method, the first layer cycle points to the day of purchase , The time complexity of finding the most profitable transaction every day after the second layer loop traverses is O(n²):
Co ownership n God , The first a Tianmai , The first b Days to sell , We need to ensure that a < b; Total number of transaction schemes available (n-1)+(n-2)+···+2+1=(n-1)n/2.
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int res = 0;
int max = 0;
for(int i = 0;i<len;i++){
for(int j = i+1;j<len;j++){
res = prices[j]-prices[i];
max = Math.max(res,max);
}
}
return max;
}
}
Time complexity is too high , Consider using dynamic programming to reduce time complexity .
State definition : set up dp Array dp[i] To i The maximum profit of all feasible transactions within days , The former i Maximum profit per day .
Transfer equation : Before the analysis i The maximum profit per day is the former i-1 Day maximum profit and day i Day selling profit whichever is greater .
d p [ i ] = m a x { d p [ i − 1 ] , p r i c e s [ i ] − m i n ( p r i c e s [ 1 : i ) ] } dp[i]=max\{dp[i-1],prices[i]-min(prices[1:i)]\} dp[i]=max{ dp[i−1],prices[i]−min(prices[1:i)]}
front i Japan most Big benefit Moisten = m a x ( front ( i − 1 ) Japan most Big benefit Moisten , The first i Japan price grid − front i Japan most low price grid ) front i Maximum daily profit =max( front (i−1) Maximum daily profit , The first i Daily price − front i Daily minimum price ) front i Japan most Big benefit Moisten =max( front (i−1) Japan most Big benefit Moisten , The first i Japan price grid − front i Japan most low price grid )
Among them, before getting i The time complexity of the daily lowest price is O(i); You can use a variable to save when traversing the array .
Reduce the time complexity again O(i) To O(1), That is, the transfer equation can be obtained by traversing the array once :
d p [ i ] = m a x { d p [ i − 1 ] , p r i c e s [ i ] − m i n ( m i n P r i c e , p e i c e s [ i ] ) } dp[i]=max\{dp[i-1],prices[i]-min(minPrice,peices[i])\} dp[i]=max{ dp[i−1],prices[i]−min(minPrice,peices[i])}
Reduce space complexity : Because only find dp Maximum of , So you can use a variable instead of dp Array
p r o f i t = m a x ( p r o f i t , p r i c e s [ i ] − m i n ( m i n P r i c e s , p r i c e s [ i ] ) ) profit = max(profit,prices[i]-min(minPrices,prices[i])) profit=max(profit,prices[i]−min(minPrices,prices[i]))
Finally, the time complexity is O(n), The space complexity is O(1)
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0){
return 0 ;
}
int len = prices.length;
int res = prices[0];
int max = 0;
for(int i = 1;i<len;i++){
// Before recording i Daily minimum
if(res>=prices[i]){
res = prices[i];
}
// Update maximum profit
max = Math.max(max,prices[i]-res);
}
return max;
}
}
3 Buckle address
https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/58vmds/
边栏推荐
猜你喜欢

What kind of experience is it to read other people's code

做一篇人人能搞懂的ThreadLocal(源码)

PostgreSQL 15新版本特性解读(含直播问答、PPT资料汇总)

【微服务|Sentinel】热点规则|授权规则|集群流控|机器列表
![[XMAN2018排位赛]通行证](/img/eb/7bf04941a96e9522e2b93859266cf2.png)
[XMAN2018排位赛]通行证

Pisa-Proxy 之 SQL 解析实践

Reflection learning summary
![[PHP code injection] common injectable functions of PHP language and utilization examples of PHP code injection vulnerabilities](/img/19/9827a5e8becfc9d5bf2f51bddf803e.png)
[PHP code injection] common injectable functions of PHP language and utilization examples of PHP code injection vulnerabilities

隐私计算FATE-离线预测

以前国产手机高傲定价扬言消费者爱买不买,现在猛降两千求售
随机推荐
【业务安全03】密码找回业务安全以及接口参数账号修改实例(基于metinfov4.0平台)
AcWing 第57 场周赛
隱私計算FATE-離線預測
每日3题(1):找到最近的有相同 X 或 Y 坐标的点
Kyndryl与Oracle和Veritas达成合作
赛迪顾问发布《“十四五” 关键应用领域之数据库市场研究报告》(附下载)
External memory
Bidding announcement: Oracle database maintenance service procurement of the First Affiliated Hospital of Jinan University
Li Kou's 81st biweekly match
Notes learning summary
全球芯片市场或陷入停滞,中国芯片逆势扩张加速提升自给率
Learning records of numpy Library
Buuctf Misc
外部存储器
【mysql进阶】MTS主从同步原理及实操指南(七)
直播app运营模式有哪几种,我们该选择什么样的模式?
A brief analysis of the differences between domestic and foreign e-commerce
Redis persistence
Axi bus
[problem solving] which nodes are run in tensorflow?