当前位置:网站首页>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/
边栏推荐
- 跨境电商多商户系统怎么选
- 剑指 Offer II 039. 直方图最大矩形面积 单调栈
- A brief analysis of the differences between domestic and foreign e-commerce
- 一次性彻底解决 Web 工程中文乱码问题
- Is there any discount for opening an account now? Is it safe to open an account online?
- 力扣 第 81 场双周赛
- CCID Consulting released the database Market Research Report on key application fields during the "14th five year plan" (attached with download)
- Half find (half find)
- [PHP code injection] common injectable functions of PHP language and utilization examples of PHP code injection vulnerabilities
- Quickly set up a website to visit foreign countries, set up SS and start BBR to quickly surf the Internet
猜你喜欢

Too many requests at once, and the database is in danger

赛迪顾问发布《“十四五” 关键应用领域之数据库市场研究报告》(附下载)

Buuctf Misc

Reflection learning summary

Kyndryl与Oracle和Veritas达成合作

类模板中可变参的逐步展开

初识云原生安全:云时代的最佳保障

What is the difference between the FAT32 and NTFS formats on the USB flash disk

基于 xml 配置文件的入门级 SSM 框架整合

OpenSSF安全计划:SBOM将驱动软件供应链安全
随机推荐
Getting to know cloud native security for the first time: the best guarantee in the cloud Era
全球芯片市场或陷入停滞,中国芯片逆势扩张加速提升自给率
Is there any discount for opening an account now? Is it safe to open an account online?
巧用redis实现点赞功能,它不比mysql香吗?
Library management system
海量数据!秒级分析!Flink+Doris构建实时数仓方案
enable_ if
2022-06-27日报:Swin Transformer、ViT作者等共话:好的基础模型是CV研究者的朴素追求
Number of printouts (solved by recursive method)
POSIX AIO -- Introduction to glibc version asynchronous IO
Implementing springboard agent through SSH port forwarding configuration
海外仓知识科普
基于 xml 配置文件的入门级 SSM 框架整合
[WUSTCTF2020]girlfriend
How to solve the problem of missing language bar in win10 system
[business security-04] universal user name and universal password experiment
[WUSTCTF2020]girlfriend
At a time of oversupply of chips, China, the largest importer, continued to reduce imports, and the United States panicked
Summary and Thinking on interface test automation
易周金融 | Q1手机银行活跃用户规模6.5亿;理财子公司布局新兴领域