当前位置:网站首页>Dynamic programming to solve stock problems (Part 1)
Dynamic programming to solve stock problems (Part 1)
2022-06-25 11:17:00 【Xia'an】
Dynamic programming solves the stock problem ( On )
1. The best time to buy and sell stocks
Title Description
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.
Force link :https://leetcode.cn/problems/best-time-to-buy-and-sell-stock
Answer key
Ideas : The overall goal is to find two numbers , To maximize the difference , And the small one is on the left
- We can build a bp Array , The profit of each sale is stored in the noodles , Write it down as profit = The number behind - The previous numbers finally compare the maximum value of all profits
- Every time you make a profit , We first find the smallest number , Write it down as
startThen traverse backwards , Find the difference between the following number and this number , namelyprofitEvery timeprofit, Compare with the last timeprofitWho is big , Take the largest value if you encounter a smaller number , We will againstartto update
/** * @param {number[]} prices * @return {number} */
var maxProfit = function(prices) {
const length = prices.length;
let start = prices[0], profit = 0;
for(let i = 0; i < length; i++) {
start = Math.min(start, prices[i]);
profit = Math.max(profit, prices[i] - start);
}
return profit;
};
2. The best time to buy and sell stocks II
Title Description
Give you an array of integers prices , among prices[i] Represents a stock i Sky price .
Every day , You can decide whether to buy and / Or sell shares . You at any time most Can only hold A wave of Stocks . You can also buy... First , And then in On the same day sell .
return What you can get Maximum profits .
Example 1:
Input :prices = [7,1,5,3,6,4]
Output :7
explain : In the 2 God ( Stock price = 1) Buy when , In the 3 God ( Stock price = 5) Sell when , The exchange will make a profit = 5 - 1 = 4 .
And then , In the 4 God ( Stock price = 3) Buy when , In the 5 God ( Stock price = 6) Sell when , The exchange will make a profit = 6 - 3 = 3 .
The total profit is 4 + 3 = 7 .
Example 2:
Input :prices = [1,2,3,4,5]
Output :4
explain : In the 1 God ( Stock price = 1) Buy when , In the 5 God ( Stock price = 5) Sell when , The exchange will make a profit = 5 - 1 = 4 .
The total profit is 4 .
Example 3:
Input :prices = [7,6,4,3,1]
Output :0
explain : under these circumstances , There is no positive profit from trading , So you can get the maximum profit by not participating in the transaction , The biggest profit is 0 .
Force link :https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
Answer key
Define the State dp[i][0] It means the first one i The maximum profit of holding shares after trading for days ,dp[i][1] It means the first one i After days of trading, there is no maximum profit of any stock in hand (i from 0 Start ).
consider dp[i][0] Transfer equation of , The possible transfer status is that one stock has been held the previous day , namely dp[i−1][0], Or there were no stocks at the end of the previous day , namely dp[i−1][1], At this time, we want to buy it , And reduce prices[i] Revenue . The following transfer equations can be listed :dp[i][0]=max{dp[i−1][0], dp[i−1][1]−prices[i]}
Consider again dp[i][1], Consider the transition state in the same way , If there is no stock in hand after trading on this day , Then the possible transition state is that there are no stocks the day before , namely dp[i−1][1], Or hold a stock at the end of the previous day , namely dp[i−1][0], At this time we have to sell it , And get prices[i] Revenue . So in order to maximize revenue , We list the following transfer equations :dp[i][0]=max{dp[i−1][0],dp[i−1][1]+prices[i]}
For the initial state , According to the definition of state, we can know that 0 At the end of the day dp[0][0]=−prices[0],dp[0][1]=0.
therefore , We just need to calculate the state from front to back . Because after the end of all transactions , The income from holding shares must be lower than that from not holding shares , So this time dp[length−1][1] The benefits must be greater than dp[length−1][0] Of , The final answer is dp[length−1][1].
/** * @param {number[]} prices * @return {number} */
var maxProfit = function(prices) {
const length = prices.length;
const dp = Array(length).fill(0).map(() => Array(2).fill(0));
dp[0][0] = - prices[0];
for(let i = 1; i < length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return dp[length - 1][1];
};
Of course , Can be set by dp0 and dp1 Two variables instead dp[i][0] and dp[i][1], Reduce space complexity .
/** * @param {number[]} prices * @return {number} */
var maxProfit = function(prices) {
const length = prices.length;
let dp0 = -prices[0];
let dp1 = 0;
for(let i = 1; i < length; i++) {
dp0 = Math.max(dp0, dp1 - prices[i]);
dp1 = Math.max(dp1, dp0 + prices[i]);
}
return dp1;
};
3. The best time to buy and sell stocks includes handling fees
Title Description
Given an array of integers prices, among prices[i] It means the first one i Day's share price ; Integers fee Represents the handling fee for trading shares .
You can close the deal indefinitely , But you have to pay a handling fee for every transaction . If you have bought a stock , You can't buy any more stock until you sell it .
Return the maximum profit .
Be careful : A deal here refers to the whole process of buying, holding and selling stocks , You only need to pay a handling fee for each transaction .
Example 1:
Input :prices = [1, 3, 2, 8, 4, 9], fee = 2
Output :8
explain : The maximum profit that can be achieved :
Buy... Here prices[0] = 1
Sell... Here prices[3] = 8
Buy... Here prices[4] = 4
Sell... Here prices[5] = 9
Total profit : ((8 - 1) - 2) + ((9 - 4) - 2) = 8
Example 2:
Input :prices = [1,3,7,5,10,3], fee = 3
Output :6
Force link :https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
Answer key
Define the State dp[i][0] It means the first one i The maximum profit of holding shares after trading for days ,dp[i][1] It means the first one i I don't have the maximum profit of the stock in my hand after trading (i from 0 Start ).
consider dp[i][0] Transfer equation of , Then the possible transfer status is that you have held a stock the previous day , namely dp[i−1][0], Or there were no stocks at the end of the previous day , namely dp[i−1][0], At this time, we want to buy it , And reduce prices[i] Revenue . The following transfer equations can be listed :dp[i][0]=max{dp[i−1][0], dp[i−1][1]−prices[i]}
Then consider in the same way dp[i][1] Transfer by status , If there is no stock in hand after trading on this day , Then the possible transition state is that there are no stocks the day before , namely dp[i−1][1], Or hold a stock at the end of the previous day , namely dp[i−1][0], At this time we have to sell it , And get prices[i] Revenue , But you have to pay fee The handling charge . So in order to maximize revenue , We list the following transfer equations :dp[i][1]=max{dp[i−1][1],dp[i−1][0]+prices[i]−fee}
For the initial state , According to the definition of state, we can know that 0 At the end of the day, there was dp[0][1]=0 as well as dp[0][0]=−prices[0].
therefore , We just need to calculate the state from front to back . Because after the end of all transactions , The income from holding shares must be lower than that from not holding shares , So this time dp[length−1][1] The benefits must be greater than dp[length−1][1] Of , The final answer is dp[length−1][1].
Of course , Can be set by dp0 and dp1 Two variables instead dp[i][0] and dp[i][1], Reduce space complexity .
/** * @param {number[]} prices * @param {number} fee * @return {number} */
var maxProfit = function(prices, fee) {
const length = prices.length;
let [dp0, dp1] = [-prices[0], 0];
for(let i = 0; i < length; i++) {
dp0 = Math.max(dp0, dp1 - prices[i]);
dp1 = Math.max(dp1, dp0 + prices[i] - fee);
}
return dp1;
};
边栏推荐
- Detection and analysis of simulator in an app
- MySQL synchronous data configuration and shell script implementation
- 撸一个随机数生成器
- Task03 probability theory
- Kingbasees plug-in DBMS of Jincang database_ OUTPUT
- FPGA displays characters and pictures based on VGA
- Some assembly instructions specific to arm64
- 每日3題(3)-檢查整數及其兩倍數是否存在
- Geographic location system based on openstreetmap+postgis paper documents + reference papers + project source code and database files
- 16 种企业架构策略
猜你喜欢

视频会议一体机的技术实践和发展趋势

Shen Lu, China Communications Institute: police open source Protocol - ofl v1.1 Introduction and Compliance Analysis

Double buffer transparent encryption and decryption driven course paper + project source code based on minifilter framework

一个数学难题,难倒两位数学家

基於Minifilter框架的雙緩沖透明加解密驅動 課程論文+項目源碼

報名開啟|飛槳黑客馬拉松第三期如約而至,久等啦

FPGA displays characters and pictures based on VGA

龙书虎书鲸书啃不动?试试豆瓣评分9.5的猴书

FPGA基于VGA显示字符及图片

NuxtJS实战案例
随机推荐
[maintain cluster case set] gaussdb query user space usage
Oracle彻底卸载的完整步骤
2022 PMP project management examination agile knowledge points (2)
Comparison between relu and SIGMOD
Previous string inversion topic
Is it safe to open an account through mobile phone if you open an account through stock speculation? Who knows?
查询法,中断法实现USART通信
Sign up to open the third session of the "flying oar hacker marathon". It's been a long time
Spannable 和 Editable、SpannableString 和 SpannableString
XSS attack
从GEE中免费获取全球人类住区层 (GHSL) 数据集
Introduction to socket UDP and TCP
Spannable and editable, spannablestring and spannablestring
Android: generic mapping analysis of gson and JSON in kotlin
COSCon'22 讲师征集令
NuxtJS实战案例
Is it safe for Guosen Securities to open a securities account
Tidb applicable scenarios
A difficult mathematical problem baffles two mathematicians
Open source invites you to participate in the openssf Open Source Security Online Seminar