当前位置:网站首页>Dynamic programming problem (VIII)
Dynamic programming problem (VIII)
2022-07-29 00:21:00 【std i hurt o love】
One 、 raid homes and plunder houses ( One )
solution : Dynamic programming
Some people may think that the use of greed , Just steal the most money from others , Either even or odd number of all the money , But sometimes in order to steal more money , Maybe they will give up two companies without stealing , So this scheme is not feasible , We still consider dynamic programming .
- use dp[i] The length is i Array of , How much money can you steal at most , As long as each transition state is gradually accumulated, you can get the money that the whole array can steal .
- If the array length is 1, Only one family , It must have stolen the family , The most profitable , therefore dp[1]=nums[0]
- Every time for a family , We choose to steal him or not , If we choose to steal, then the previous one must not steal , Therefore, the maximum benefit of the accumulated superior , Similarly, if you choose not to steal him , Then we can accumulate up to one level of income . So the transfer equation is dp[i]=max(dp[i−1],nums[i−1]+dp[i−2]). there i stay dp Array length in , stay nums Middle is the subscript .

class Solution {
public:
int rob(vector<int>& nums) {
//dp[i] The length is i Array of , How much money can you steal at most
vector<int> dp(nums.size() + 1, 0);
// The length is 1 Only the first one can be stolen
dp[1] = nums[0];
for(int i = 2; i <= nums.size(); i++)
// For each family, you can choose to steal or not
dp[i] = max(dp[i - 1], nums[i - 1] + dp[i - 2]);
return dp[nums.size()];
}
};
Time complexity :O(n), among n Is array length , Traversing the array once
Spatial complexity :O(n), Dynamically plan the space of auxiliary array
Two 、 raid homes and plunder houses ( Two )
solution : Dynamic programming
Using the original scheme is : use dp[i] The length is i Array of , How much money can you steal at most , As long as each transition state is gradually accumulated, you can get the money that the whole array can steal .
If the array length is 1, Only one family , It must have stolen the family , The most profitable , therefore dp[1]=nums[0]
Every time for a family , We choose to steal him or not , If we choose to steal, then the previous one must not steal , Therefore, the maximum benefit of the accumulated superior , Similarly, if you choose not to steal him , Then we can accumulate up to one level of income . So the transfer equation is dp[i]=max(dp[i−1],nums[i−1]+dp[i−2]). there i stay dp Array length in , stay nums Middle is the subscript .
At this time, the first house and the last house cannot get , Then we can discuss it in two situations :
situation 1: Steal money from the first house , Don't steal the last family's money . The initial state and state transition remain unchanged , Only when traversing, the last bit of the array is not traversed .
situation 2: Steal the last one please , Don't steal money from the first house . The initial state is set dp[1]=0, Not the first one , Then, when traversing, it will also traverse to the last bit of the array .
- Finally, take the larger value of the two cases .
class Solution {
public:
int rob(vector<int>& nums) {
//dp[i] The length is i Array of , How much money can you steal at most
vector<int> dp(nums.size() + 1, 0);
// Choose to steal the first
dp[1] = nums[0];
// The last one can't steal
for(int i = 2; i < nums.size(); i++)
// For each family, you can choose to steal or not
dp[i] = max(dp[i - 1], nums[i - 1] + dp[i - 2]);
int res = dp[nums.size() - 1];
// eliminate dp Array , The second cycle
dp.clear();
// Don't steal the first one
dp[1] = 0;
// You can steal the last one
for(int i = 2; i <= nums.size(); i++)
// For each family, you can choose to steal or not
dp[i] = max(dp[i - 1], nums[i - 1] + dp[i - 2]);
// Select the maximum value
return max(res, dp[nums.size()]);
}
};
Time complexity :O(n), among n Is array length , Traverse the array twice alone
Spatial complexity :O(n), Dynamically plan the space of auxiliary array
3、 ... and 、 The best time to buy and sell stocks ( One )
Solution 1 : Dynamic programming ( recommend )
- use dp[i][0] It means the first one i Day does not hold the maximum return until that day ,dp[i][1] It means the first one i Tian Holdings , Maximum gain to date .
- Day one does not hold shares , Then the total income is 0,dp[0][0]=0; The first day , Then the total income is the cost of buying stocks , This is a negative number ,dp[0][1]=−prices[0]
- For every day after that , If you do not hold shares on that day , It may have been sold or not bought in the past few days , So the total income so far is the same as the previous day , It may also be sold on the same day , We choose the larger state dp[i][0]=max(dp[i−1][0],dp[i−1][1]+prices[i]);
- If shares are held on the same day , It may be that I bought stocks in the previous few days , Not sold that day , So the return is the same as the day before , It is also possible to buy on the same day , At this time, the stock price with negative return , The same is to select the maximum value :dp[i][1]=max(dp[i−1][1]−prices[i]).
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
//dp[i][0] Indicates the maximum return of non holding shares until that day ,dp[i][1] It means holding shares one day , Maximum gain to date
vector<vector<int> > dp(n, vector<int>(2, 0));
// Day one does not hold shares , The total revenue is 0
dp[0][0] = 0;
// The first day , The total income is minus the share price of that day
dp[0][1] = -prices[0];
// Traverse the next day , State shift
for(int i = 1; i < n; i++){
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1] = max(dp[i - 1][1], -prices[i]);
}
// Not holding shares on the last day , Maximum gain to date
return dp[n - 1][0];
}
};
Time complexity :O(n), among n Is array length , Traversing the array once
Spatial complexity :O(n), Dynamically plan the space of auxiliary array
Solution 2 : greedy
If we sell shares one day , So to get the most out of it , It must be the stock it bought on the day of the lowest price in front of it . So we can use greed to solve , Subtract the daily income from the minimum price every time to maintain the maximum value .
- First, exclude the special case that the array is empty .
- Think of the first day as the lowest price , If the price is lower during subsequent traversal, the update price is the lowest .
- Each time, compare the maximum return with the price of the day minus the lowest price , Select the maximum value as the maximum benefit .
class Solution {
public:
int maxProfit(vector<int>& prices) {
// Maintain maximum benefits
int res = 0;
// Exclude special circumstances
if(prices.size() == 0)
return res;
// Maintain the minimum stock price
int Min = prices[0];
// Traverse subsequent stock prices
for(int i = 1; i < prices.size(); i++){
// If the price of the day is lower, update the lowest price
Min = min(Min, prices[i]);
// Maintenance maximum
res = max(res, prices[i] - Min);
}
return res;
}
};
Time complexity :O(n), among n Is array length , Traverse the array at once
Spatial complexity :O(1), Constant level variable , No additional auxiliary space
边栏推荐
- Everything you have learned will come in handy at some point in your life (turn)
- Develop effective Tao spell
- Where is sandbox's confidence in rejecting meta's acquisition of meta universe leader sand?
- 研发效能的道法术器
- 还在写大量 if 来判断?一个规则执行器干掉项目中所有的 if 判断...
- 【C】 Replace spaces and realize binary parity bit exchange of integers by macros
- Advanced area of attack and defense world web masters training www robots
- Samsung asset management (Hong Kong) launched yuancosmos ETF to focus on investing in the future tuyere track
- Kali installs burpsuite professional
- AutoCAD -- import excel tables into CAD and merge CAD
猜你喜欢

【MySQL系列】MySQL数据库基础

MySQL transaction (this is enough...)

Event extraction and documentation (2018)

Detailed explanation of 9 common reasons for MySQL index failure

Leetcode62. Different paths

Have passed hcip and joined the company of your choice, and share the learning experience and experience of Huawei certification

Real time data warehouse: meituan's implementation of real-time data warehouse construction based on Flink

Using recursion and chain header interpolation to realize the group turnover of linked lists -- leetcode25 K group turnover linked lists

聊聊异步编程的 7 种实现方式

centos7安装mysql8
随机推荐
【MySQL系列】MySQL数据库基础
Camera Hal OEM模块 ---- cmr_preview.c
MQ 消息丢失、重复、积压问题,如何解决?
vscode下链接远程服务器安装插件失败、速度慢等解决方法
Feign call fails. JSON parse error illegal character ((ctrl-char, code 31)) only regular white space (R
SQL实现将多行记录合并成一行
ACM SIGIR 2022 | interpretation of selected papers of meituan technical team
Recursion / backtracking (Part 2)
Web系统常见安全漏洞介绍及解决方案-CSRF攻击
Idea connection database
Where is sandbox's confidence in rejecting meta's acquisition of meta universe leader sand?
还在写大量 if 来判断?一个规则执行器干掉项目中所有的 if 判断...
Data warehouse: Doris' application practice in meituan
Summary of wrong questions of software designers
“Method Not Allowed“,405问题分析及解决
#{}和${}的区别
Detailed explanation of 9 common reasons for MySQL index failure
SQL implementation merges multiple rows of records into one row
[CNN] Why is the convolution kernel size of CNN usually odd
Install mysql5.7 under Linux, super detailed complete tutorial, and cloud MySQL connection