当前位置:网站首页>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 
边栏推荐
猜你喜欢

torch. logical_ And() method

Background position - mixed units

The database doesn't know what went wrong

Background position position NOUN

MFS explanation (IV) -- MFS management server installation and configuration

Flink CheckPoint : Exceeded checkpoint tolerable failure threshold

MFS详解(四)——MFS管理服务器安装与配置

网页中加载二次元3D虚拟主播源码(1:项目介绍和源码)

《MATLAB 神經網絡43個案例分析》:第7章 RBF網絡的回歸--非線性函數回歸的實現
![[data storage] storage of floating point data in memory](/img/c4/a67735858ce5d58bd504b087a2d123.png)
[data storage] storage of floating point data in memory
随机推荐
(十二)交互组件Selectable
Jump to an interface at a specified time. (Web Development)
The difference between deep copy and shallow copy
Gets the number of occurrences of a character in a string
Random acquisition of 4-digit non repeated verification code
Convert spaces to < br / > newline labels
2022.6.11-----leetcode.926
Unittest测试框架
Chapter 8 - two basic problems of data processing
深拷贝与浅拷贝的区别
Get last month, current time and next month
[character set 8] char8_ t、char16_ t、char32_ t、wchar、char
MFS explanation (IV) -- MFS management server installation and configuration
Use NVM to dynamically adjust the nodejs version to solve the problem that the project cannot be run and packaged because the node version is too high or too low
About weights exercise
Application method of new version UI of idea + use method of non test qualification and related introduction
Knee joint
[GUI development] browsing function implementation model of image processing software
Introduction to applet cloud development -- questionnaire evaluation applet practice (7)
API处理Android安全距离








