当前位置:网站首页>LeetCode 122:买卖股票的最佳时机 II
LeetCode 122:买卖股票的最佳时机 II
2022-07-26 21:38:00 【斯沃福德】
题目:
思路:动态规划
上一题最大交易次数K=1,而此题不限制K,即K为无穷,
则两个状态转移方程:
- 今天没有:昨天也没有 + 昨天有、卖了
- 今天持有:昨天也持有 + 昨天没有、买了

由于数组中的 k 已经不会改变了,也就是说不需要记录 k 这个状态了:
Java实现:
注意:
代码部分和上一题121几乎一样,
区别在于 求今天有时, 昨天没有、今天买了是 dp[i-1][0]-prices[i] ,符合逻辑;
而121题是 -prices[i] !!!
class Solution {
public int maxProfit(int[] prices) {
int n=prices.length;
int[][] dp=new int[n][2];
// base case
dp[0][0]=0;
dp[0][1]=-prices[0];
// 遍历状态
for(int i=1;i<n;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[n-1][0];
}
}
边栏推荐
猜你喜欢

Altium designer 22 Chinese character garbled

Altium designer 22 modify the layer properties of the selected component

新兴市场潜力无限,ADVANCE.AI风控产品助中国出海企业筑牢安全发展基础

The principle of normal equation method and its difference from gradient descent method

OPPO 自研大规模知识图谱及其在数智工程中的应用

06 cp 命令

Flink's real-time data analysis practice in iFLYTEK AI marketing business

09.01 深度优先搜索

Let me show you the MySQL isolation level. What happens when two transactions operate on the same row of data at the same time?

Summary of debugging stc8a8k64d4 MCU 485 communication
随机推荐
什么是 Base64 ?
ORM uses different data sources and different naming transformations at the same time
Props with type Object/Array must...
Unity operates on Explorer, opens explorer, selects files, and filters files
[try to hack] firewall (I)
: could not determine a constructor for the tag ! RootAdmin
蔚来杯2022牛客暑期多校训练营1
08 Du command
yolov1
实际权威来自信息优势
jmeter -- response中文乱码处理
C data type_ From rookie tutorial
Oppo self-developed large-scale knowledge map and its application in digital intelligence engineering
MySQL recommendation
matlab 基音周期估计后处理
[RequireComponent(typeof(....))]
Is it safe to open an account on flush? How to choose a securities firm for opening an account
Operating guidelines and suggestions for spot gold (Part 1)
JS verify complex password
Li Kou daily question - day 43 -168. Name of Excel table column