当前位置:网站首页>Offer:[day 8 dynamic planning (simple)] --- > maximum profit of stock
Offer:[day 8 dynamic planning (simple)] --- > maximum profit of stock
2022-06-12 08:56:00 【Love you, little pig】
List of articles
One 、 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 ?
Example 1:
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 .
Example 2:
Input : [7,6,4,3,1]
Output : 0
explain : under these circumstances , No deal is done , So the biggest profit is 0.
Limit :0<= The length of the array <=10^5
Two 、 Thought analysis
notes : Some contents and pictures in the train of thought analysis refer to the solutions of your predecessors , Thank them for their selfless dedication
Dynamic programming ---- Conventional methods
front
iMaximum daily profitdp[i]Equal to beforei-1Maximum daily profitdp[i-1]And theiThe maximum of the maximum profit sold on the day .
frontiMaximum daily profit = max( front ( i − 1 i-1 i−1) Maximum daily profit , The first i i i Daily price − - − front i i i Daily minimum price )
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 [ 0 : i ] ) ) \rm{dp[i]=max(dp[i−1],prices[i]−min(prices[0:i]))} dp[i]=max(dp[i−1],prices[i]−min(prices[0:i]))
Efficiency optimization :
① Reduced time complexity : frontiThe lowest price per day m i n ( p r i c e s [ 0 : i ] ) \rm{min(prices[0:i])} min(prices[0:i]) The time complexity isO(i). And traversingpriceswhen , With the help of a variable ( Recorded as costcost) Update the minimum price every day .
② Reduced space complexity : becausedp[i]Only withdp[i-1]、prices[i]、costrelevant , So you can use a variable ( Recorded as profitprofit) Update the maximum profit every day .
Complexity analysis :
Time complexity O ( N ) \rm{O(N)} O(N): amongNbypricesList length , Dynamic planning needs to traverseprices
Spatial complexity O ( 1 ) \rm{O(1)} O(1): VariablecostandprofitUse extra space of constant size .
Dynamic programming ---- Online processing
Algorithm flow :
① Define two variablesmaxandtmp, Represents maximum profit and current profit
② Traversing an array , The current profit is accumulated at each cycle ,tmp+=rices[i]-prices[i-1]
③ If current profitstmpGreater than the maximum profitmax, Then update the maximum profitmaxValue .
③ IftmpLess than or equal tomax, alsotmpLess than0, So it means that no matter what number is added later, it will only make the sum smaller and smaller , We might as well start from scratch , thereforetmpSet as0.
Complexity analysis :
Time complexity O ( N ) \rm{O(N)} O(N): amongNbypricesList length , Dynamic planning needs to traverseprices
Spatial complexity O ( 1 ) \rm{O(1)} O(1): VariabletmpandmaxUse extra space of constant size .
3、 ... and 、 The overall code
The overall code of the conventional method of dynamic planning is as follows
int maxProfit(int* prices, int pricesSize){
int cost = 1e9;
int profit = 0;
for(int i = 0; i < pricesSize; i++){
cost = cost <= prices[i]? cost : prices[i];
profit = profit >= (prices[i]-cost)? profit : (prices[i]-cost);
}
return profit;
}
function , The test passed 
The overall code of the dynamic planning online processing method is as follows
int maxProfit(int* prices, int pricesSize){
int max = 0;
int tmp = 0;
for(int i = 1; i < pricesSize; i++){
tmp += prices[i]-prices[i-1];
if(tmp > max){
max = tmp;
}
else if(tmp < 0){
tmp = 0;
}
}
return max;
}
function , The test passed 
边栏推荐
- Oracle installation details (verification)
- IDEA新版UI申请方法+无测试资格使用方法及相关介绍
- Random acquisition of 4-digit non repeated verification code
- Flink CheckPoint : Exceeded checkpoint tolerable failure threshold
- Knowledge points of 2022 system integration project management engineer examination: project cost management
- Dynamically create and submit forms
- 处理异常数据
- [advanced pointer 2] array parameter transfer & pointer parameter transfer & function pointer & function pointer array & callback function
- 第五章-[bx]和Loop指令
- Background position - mixed units
猜你喜欢

Union selector

Background fixing effect

Engineers learn music theory (I) try to understand music
![(node:22344) [DEP0123] DeprecationWarning: Setting the TLS ServerName to an IP address is not permit](/img/c1/d56ec09663857afa52f20848aeadac.png)
(node:22344) [DEP0123] DeprecationWarning: Setting the TLS ServerName to an IP address is not permit

Background location case 1

最少换乘次数
![[compilation principle] understand BNF](/img/64/9a0e7507606781336fdc44116ba423.jpg)
[compilation principle] understand BNF

了结非对称密钥

【字符集七】汉字的宽字符码和多字节码分别是多少

第三章 寄存器 (内存访问)
随机推荐
深拷贝与浅拷贝的区别
2022.6.11-----leetcode.926
UMI packaging and subcontracting, and compressing to gzip
Graphic analysis of viewbox in SVG
【字符集六】宽字符串和多字节字符互转
Engineers learn music theory (I) try to understand music
Does database and table splitting cause reading diffusion problems? How to solve it?
[open source project] easycmd command graphical software
ip、DNS、域名、URL、hosts
Introduction to Chang'an chain node certificate, role and authority management
[essence] explain in detail the memory management mechanism in QT
Introduction to applet cloud development -- questionnaire evaluation applet practice (7)
(十五) TweenRunner
目标识别、检测和 6D 姿态估算源码与方案(最先进的方法和数据集)
Engineers learn music theory (III) interval mode and chord
Build personal blog and web.
POI library update excel picture
Background position - exact units
Get last month, current time and next month
mySql学习记录——二、mySql建表命令








