当前位置:网站首页>The best time to buy and sell stocks (leetcode-121)
The best time to buy and sell stocks (leetcode-121)
2022-07-24 09:54:00 【Casten-Wang】
The best time to buy and sell stocks (LeetCode-121)
subject
Given an array prices , It's the first i Elements prices[i] Represents the number of shares in a given stock i Sky price .
You can only choose One day Buy this stock , And choose A different day in the future Sell the stock . Design an algorithm to calculate the maximum profit you can get .
Return the maximum profit you can make from the deal . If you can't make any profit , return 0 .
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 ; meanwhile , You can't sell stocks before you buy them .
Example 2:
Input :prices = [7,6,4,3,1]
Output :0
explain : under these circumstances , No deal is done , So the biggest profit is 0.
Tips :
1 <= prices.length <= 1050 <= prices[i] <= 104
Ideas
dp[i][ take 0 or 1]The meaning of- d p [ i ] [ 0 ] dp[i][0] dp[i][0] It means the first one i i i Cash from holding the stock for days
- d p [ i ] [ 1 ] dp[i][1] dp[i][1] It means the first one i i i Cash from not holding the stock for days
The recursive formula
- d p [ i ] [ 0 ] dp[i][0] dp[i][0] Can be derived from two states
- The first i − 1 i-1 i−1 Days holding shares , It is equal to d p [ i − 1 ] [ 0 ] dp[i-1][0] dp[i−1][0]
- The first i i i Days to buy shares , The cash will be after buying today − p r i c e [ i ] -price[i] −price[i]
- Choose the one with the most cash , That is, the greater of the two
- d p [ i ] [ 1 ] dp[i][1] dp[i][1] Can be derived from two states
- The first i − 1 i-1 i−1 Days do not hold shares , It is equal to d p [ i − 1 ] [ 0 ] dp[i-1][0] dp[i−1][0]
- The first i i i Days to sell shares , It is equal to p r i c e [ i ] + d p [ i − 1 ] [ 0 ] price[i]+dp[i-1][0] price[i]+dp[i−1][0]
- Choose the one with the most cash , That is, the greater of the two
- d p [ i ] [ 0 ] dp[i][0] dp[i][0] Can be derived from two states
Array initialization
dp[0][0]It means the first one 0 Days holding shares , So it's equal to − p r i c e [ 0 ] -price[0] −price[0]dp[0][1]It means the first one 0 Days do not hold shares , be equal to 0
traversal order
- Before and after
The test case

Go through the use case in your own mind and you'll understand
Code display
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
int n = prices.size();
vector<vector<int>> dp(n, vector<int>(2));
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; i++)
{
dp[i][0] = max(dp[i - 1][0], -prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return dp[n - 1][1];
}
};
Rolling array optimization !
As can be seen from the recurrence formula ,dp[i] Just relying on dp[i - 1] The state of .
So just record the status of the previous day and the current day
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
int n = prices.size();
vector<vector<int>> dp(2, vector<int>(2));
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; i++)
{
dp[i % 2][0] = max(dp[(i - 1) % 2][0], -prices[i]);
dp[i % 2][1] = max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i]);
}
return dp[(n - 1) % 2][1];
}
};
This optimization method is really to understand the binary , I was shocked .
边栏推荐
- Will your NFT disappear? Dfinity provides the best solution for NFT storage
- Do you really understand the concept of buffer? Take you to uncover the buffer zone~
- [STM32 learning] (11) STM32 Mifare_ Use of one (S50) m1s50 (read, write, key modification, control bit interpretation)
- Is it safe for Oriental Fortune futures to open an online account, and will it be cheated?
- [don't bother to strengthen learning] video notes (III) 2. SARS learning realizes maze walking
- Arduino drive Lora module node
- [don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?
- Anti shake and throttling
- PHP caching system - PHP uses Memcache
- [200 opencv routines] 236. Principal component analysis of feature extraction (openCV)
猜你喜欢

缓冲区的概念真的理解么?带你揭开缓冲区的面纱~
![Calculate CPU utilization [Prometheus]](/img/00/d9f297e3013cabbf3d41be58105fc7.png)
Calculate CPU utilization [Prometheus]

CRC Coding in C language
![[STM32 learning] (11) STM32 Mifare_ Use of one (S50) m1s50 (read, write, key modification, control bit interpretation)](/img/fd/4290525914b5146fe0eb653517fef9.png)
[STM32 learning] (11) STM32 Mifare_ Use of one (S50) m1s50 (read, write, key modification, control bit interpretation)

C#/VB. Net: convert word or EXCEL documents to text

ASI-20220222-Implicit PendingIntent

Li Kou 300 longest increasing subsequence dynamic programming

What's the difference between testing / developing programmers' professionalism and salted fish? They don't want to be excellent coders?

error: field ‘XXX’ declared as a function
![[MySQL] - deep understanding of index](/img/a6/6ca1356fe11bd33ec7362ce7cdc652.png)
[MySQL] - deep understanding of index
随机推荐
Cess test online line! The first decentralized storage network to provide multiple application scenarios
JS bind simulation
Do you really understand the concept of buffer? Take you to uncover the buffer zone~
Why add where exists() to the update select statement? And update with a with statement
Arduino- use millis() to do two (or more) things at the same time
Openstack network neutron knowledge point "openstack"
[STM32 learning] (18) STM32 realizes LCD12864 display - parallel implementation of 8-bit bus
Development history of the first commercial humanoid biped robot in China
PHP Basics - PHP magic constants
Countdownlatch and join [concurrent programming]
AttributeError: module ‘sipbuild. api‘ has no attribute ‘prepare_ metadata_ for_ build_ wheel‘
Anti shake and throttling
A null pointer exception is reported when the wrapper class inserts into the empty field of the database table
聚集日志服务器
What are the 6% annualized products?
Scala learning: why emphasize immutable objects?
What is the cloud native mid platform business architecture?
This article takes you to understand the dynamic memory allocation of C language
Android Version Description security privacy 13
At the moment of the epidemic, we need to work harder, aoligui