- 浏览: 141193 次
-
文章分类
- 全部博客 (189)
- Tree (14)
- Dynamic Programming (34)
- Array (20)
- Search (1)
- Hash (12)
- Backtracking (22)
- Divide and Conque (8)
- Greedy (6)
- Stack (12)
- software (0)
- List (7)
- Math (22)
- Two pointers (16)
- String (20)
- Linux (1)
- Sliding Window (4)
- Finite State Machine (1)
- Breadth-first Search (7)
- Graph (4)
- DFS (6)
- BFS (3)
- Sort (9)
- 基础概念 (2)
- 沟通表达 (0)
- Heap (2)
- Binary Search (15)
- 小结 (1)
- Bit Manipulation (8)
- Union Find (4)
- Topological Sort (1)
- PriorityQueue (1)
- Design Pattern (1)
- Design (1)
- Iterator (1)
- Queue (1)
最新评论
-
likesky3:
看了数据结构书得知并不是迭代和递归的区别,yb君的写法的效果是 ...
Leetcode - Graph Valid Tree -
likesky3:
迭代和递归的区别吧~
Leetcode - Graph Valid Tree -
qb_2008:
还有一种find写法:int find(int p) { i ...
Leetcode - Graph Valid Tree -
qb_2008:
要看懂这些技巧的代码确实比较困难。我是这么看懂的:1. 明白这 ...
Leetcode - Single Num II -
qb_2008:
public int singleNumber2(int[] ...
Leetcode - Single Num II
Say you have an array for which the ith element is the price of a given stock on day i.Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
[balabala] 此题参照 网友博客的解法http://www.cnblogs.com/grandyang/p/4295761.html。需要维护两个dp数组,分别是local[i][j] 和global[i][j],前者表示到第i天为止至多完成j次交易且最后一笔交易于第i天完成的最大收益,是一个局部最优值,后者表示到第i天为止至多完成j次交易获取的最大值, 为全局最优值。global[i][j] = max(global[i - 1][j], local[i][j]), 这个递推式比较好理解,是按照第 i 天是否参与交易分类讨论的,local[i][j] = max(global[i - 1][j - 1] + max(0, diff), local[i - 1][j] + diff).
对于这个解法一度半懂不懂,为什么需要两个dp数组呢?local[][]数组的递推公式如何理解? 在理解的过程中发现可以这样去理解那些不理解的事物(说得有些绕):去掉看看效果,正确的解法里每个变量都是有其不可替换的作用的。假设我们只用一个dp数组,dp[i][j]含义同global[i][j],表示到第i天至多完成j次交易能获取的最大利润,自然地,可以按照第 i 天是否参与最后一笔交易分类讨论,于是递推公式dp[i][j] = max(dp[i - 1][j], max(dp[k][j - 1] + maxProfitBetween(k + 1, i)) ), 式中第二项表示 第i天参与交易的情况,看到仅有dp[][]数组的情况下写起来是多么复杂。于是理解了local[][]数组的好处,使算法复杂度由O(n^3)变为O(n^2)(对比Palindrome Partition II 的降维思路,目前还没看出两种降维思路的想通之处)。local[i][j]是如何递推的呢? 它的作用是记录到第 i 天至多完成 j 次交易的最大利润且第 i 天完成最后一笔交易,这最后一笔交易卖出点是day i, 买入点可以是0 - i的任意一天,分三种情况讨论:
1) 在i - 1天之前买入:这种情况下可将最后一笔交易以day[i-1]为分割点分解为两笔交易来计算,第一笔是在day[k](k < i -1)买入,day[i -1]卖出,对应于local[i - 1][j], 第二笔是day[i - 1]买入,day[i]卖出,火力为prices[i] - prices[i - 1], 于是这种情况下local[i][j] = local[i-1][j] + prices[i] - prices[i - 1]
2) 在第 i - 1天买入:local[i][j]= global[i - 1][j - 1] + prices[i] - prices[i - 1]
3) 在第 i 天买入: local[i][j]= global[i - 1][j - 1] + 0
合并起来,local[i][j] = local[i][j] = max(global[i - 1][j - 1] + max(0, diff), local[i - 1][j] + diff), 其中diff = prices[i] - prices[i - 1]
第三个实现yb君的思路,另一角度看问题~
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
[balabala] 此题参照 网友博客的解法http://www.cnblogs.com/grandyang/p/4295761.html。需要维护两个dp数组,分别是local[i][j] 和global[i][j],前者表示到第i天为止至多完成j次交易且最后一笔交易于第i天完成的最大收益,是一个局部最优值,后者表示到第i天为止至多完成j次交易获取的最大值, 为全局最优值。global[i][j] = max(global[i - 1][j], local[i][j]), 这个递推式比较好理解,是按照第 i 天是否参与交易分类讨论的,local[i][j] = max(global[i - 1][j - 1] + max(0, diff), local[i - 1][j] + diff).
对于这个解法一度半懂不懂,为什么需要两个dp数组呢?local[][]数组的递推公式如何理解? 在理解的过程中发现可以这样去理解那些不理解的事物(说得有些绕):去掉看看效果,正确的解法里每个变量都是有其不可替换的作用的。假设我们只用一个dp数组,dp[i][j]含义同global[i][j],表示到第i天至多完成j次交易能获取的最大利润,自然地,可以按照第 i 天是否参与最后一笔交易分类讨论,于是递推公式dp[i][j] = max(dp[i - 1][j], max(dp[k][j - 1] + maxProfitBetween(k + 1, i)) ), 式中第二项表示 第i天参与交易的情况,看到仅有dp[][]数组的情况下写起来是多么复杂。于是理解了local[][]数组的好处,使算法复杂度由O(n^3)变为O(n^2)(对比Palindrome Partition II 的降维思路,目前还没看出两种降维思路的想通之处)。local[i][j]是如何递推的呢? 它的作用是记录到第 i 天至多完成 j 次交易的最大利润且第 i 天完成最后一笔交易,这最后一笔交易卖出点是day i, 买入点可以是0 - i的任意一天,分三种情况讨论:
1) 在i - 1天之前买入:这种情况下可将最后一笔交易以day[i-1]为分割点分解为两笔交易来计算,第一笔是在day[k](k < i -1)买入,day[i -1]卖出,对应于local[i - 1][j], 第二笔是day[i - 1]买入,day[i]卖出,火力为prices[i] - prices[i - 1], 于是这种情况下local[i][j] = local[i-1][j] + prices[i] - prices[i - 1]
2) 在第 i - 1天买入:local[i][j]= global[i - 1][j - 1] + prices[i] - prices[i - 1]
3) 在第 i 天买入: local[i][j]= global[i - 1][j - 1] + 0
合并起来,local[i][j] = local[i][j] = max(global[i - 1][j - 1] + max(0, diff), local[i - 1][j] + diff), 其中diff = prices[i] - prices[i - 1]
第三个实现yb君的思路,另一角度看问题~
public class Solution { // Method 3: space: O(N * k), time: O(N * k) public int maxProfit(int k, int[] prices) { if (prices == null || prices.length == 0) return 0; int N = prices.length; if (N <= k - 1) return maxProfitWithoutLimit(prices); int M = 2 * k; // dp[i][j]: on day i (1, 2... N), max profit after transaction j done // transaction j means buy j / 2 + j % 2 times, sell j / 2 times int[][] dp = new int[N + 1][M + 1]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= i && j <= M; j++) { if (j % 2 == 1) {// buy dp[i][j] = dp[i - 1][j - 1] - prices[i - 1]; } else { // sell dp[i][j] = dp[i - 1][j - 1] + prices[i - 1]; } if (i - 1 >= j) dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]); } } int max = 0; for (int j = 2; j <= M; j += 2) { max = Math.max(max, dp[N][j]); } return max; } // Method 2space: O(k), time: O(N * k) public int maxProfit(int k, int[] prices) { if (prices == null || prices.length == 0) return 0; int days = prices.length; if (k >= days) return maxProfit(prices); // local[j] 表示到当日至多完成j次交易,并且最后一笔交易在当日完成的最大收益 int[] local = new int[k + 1]; // global[j] 表示到当日至多完成j次交易的最大收益 int[] global = new int[k + 1]; for (int i = 1; i < days; i++) { for (int j = k; j > 0; j--) { // 逆序以利用前一天的结果 int diff = prices[i] - prices[i - 1]; local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff); global[j] = Math.max(global[j], local[j]); } } return global[k]; } // Method 1: space: O(N * k), time: O(N * k) public int maxProfit1(int k, int[] prices) { if (prices == null || prices.length == 0) return 0; int days = prices.length; if (k >= days) return maxProfit(prices); // local[i][j] 表示到第i天至多完成j次交易,并且最后一笔交易在第i天完成的最大收益 int[][] local = new int[days][k + 1]; // global[i][j] 表示到第i天至多完成j次交易的最大收益 int[][] global = new int[days][k + 1]; for (int i = 1; i < days; i++) { local[i][0] = 0; global[i][0] = 0; for (int j = 1; j <= k; j++) { int diff = prices[i] - prices[i - 1]; local[i][j] = Math.max(global[i - 1][j - 1] + Math.max(diff, 0), local[i - 1][j] + diff); global[i][j] = Math.max(global[i - 1][j], local[i][j]); } } return global[days - 1][k]; } private int maxProfit(int[] prices) { if (prices == null || prices.length == 0) return 0; int days = prices.length; int profit = 0; int delta = 0; for (int i = 1; i < days; i++) { delta = prices[i] - prices[i - 1]; profit += delta > 0 ? delta : 0; } return profit; } }
评论
1 楼
qb_2008
2015-05-05
带进去简单例子分析一下,就知道代码为什么要这样做了。比如k = 1, prices[] = {1, 4, 3, 7}.
这个问题看成K条装配线上的N个装配站问题或许更容易理解。
N是天数,在每天你可以处于2*k+1种交易状态,让
dp[i][j]为第i天,买入j/2+j%2次,卖出j/2次的最大盈利。
dp[0][0] = 0;
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= 2 * k && j <= i; ++i) {
if (j % 2 == 1) {
// only can buy.
dp[i][j] = dp[i - 1][j - 1] - prices[i - 1];
if (i - 1 >= j) { // or keep previous value.
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);
}
} else {
// only can sell.
...
}
}
}
这个问题看成K条装配线上的N个装配站问题或许更容易理解。
N是天数,在每天你可以处于2*k+1种交易状态,让
dp[i][j]为第i天,买入j/2+j%2次,卖出j/2次的最大盈利。
dp[0][0] = 0;
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= 2 * k && j <= i; ++i) {
if (j % 2 == 1) {
// only can buy.
dp[i][j] = dp[i - 1][j - 1] - prices[i - 1];
if (i - 1 >= j) { // or keep previous value.
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);
}
} else {
// only can sell.
...
}
}
}
发表评论
-
Leetcode - Ugly Number II
2015-08-24 22:54 1183[分析] 暴力的办法就是从1开始检查每个数是否是丑数,发现丑数 ... -
Leetcode - Paint House II
2015-08-20 20:37 1626There are a row of n houses, ea ... -
Leetcode - Maximum Square
2015-08-16 13:33 537Given a 2D binary matrix filled ... -
Leetcode - Paint House
2015-08-16 10:48 1165There are a row of n houses, ea ... -
Leetcode - Different Ways to Add Parentheses
2015-07-29 20:21 1226Given a string of numbers and o ... -
Jump Game II
2015-07-05 16:49 571Given an array of non-negative ... -
Leetcode - Jump Game
2015-07-05 15:52 549Given an array of non-negative ... -
Leetcode - Interleaving String
2015-06-07 11:41 632Given s1, s2, s3, find whe ... -
Leetcode - Wildcard Matching
2015-06-06 20:01 1008Implement wildcard pattern ma ... -
Leetcode - Maximal Square
2015-06-04 08:25 637Given a 2D binary matrix fille ... -
Leetcode - Palindrome Partition II
2015-05-21 21:15 697Given a string s, partition ... -
Leetcode - Palindrome Partition
2015-05-21 09:56 805Given a string s, partition s s ... -
Leetcode - House Robber II
2015-05-20 22:34 791Note: This is an extension of ... -
Leetcode - Maximum Rectangle
2015-05-20 08:58 517Given a 2D binary matrix fill ... -
Leetcode - Scramble String
2015-05-17 14:22 604Given a string s1, we may repre ... -
Leetcode - Regular Expression Matching
2015-05-16 16:31 429Implement regular expression ma ... -
Leetcode - Distinct Subsequences
2015-05-01 16:56 534Given a string S and a string T ... -
Leetcode - Best Time to Buy and Sell Stock IV
2015-04-23 09:59 0public class Solution ... -
Leetcode - Best Time to Buy and Sell Stock III
2015-04-23 09:04 501Say you have an array for whi ... -
Leetcode - Dungeon Game
2015-04-21 09:50 484The demons had captured the pr ...
相关推荐
本篇Java题解关注的是“Best Time to Buy and Sell Stock IV”(买卖股票的最佳时机 IV),这是该系列问题中的一个变体,涉及动态规划这一算法思想。 首先,需要明确问题的具体要求。在这个变体中,给定一个数组,...
在深入探讨“java-leetcode题解之Best Time to Buy and Sell Stock III.java”这一文件内容之前,我们需要了解LeetCode平台及其题解的价值。LeetCode是一个专门面向技术面试的在线编程平台,它提供了一系列的编程...
《最佳买卖股票时机II》是LeetCode中的一道经典编程题目,主要涉及动态规划和数组操作的知识点。在这个问题中,我们被赋予一个整数数组`prices`,表示某支股票每天的价格。任务是找到在允许进行多次交易的情况下,...
在解决股票交易问题时,程序员们经常会遇到“Best Time to Buy and Sell Stock with Cooldown”这类问题。该问题属于动态规划的经典案例,通常被列为中等难度。在这类问题中,给定一个整数数组表示某只股票的价格,...
在JavaScript中,LeetCode题目"Best Time to Buy and Sell Stock III"是一个典型的数据结构和算法问题,通常出现在编程面试和算法训练中。该问题的目标是在给定的股票价格数组中找出最大的利润,但是与简单买卖一次...
python python_leetcode题解之123_Best_Time_to_Buy_and_Sell_Stock_III
- 题目理解:Best Time to Buy and Sell Stock II这道题目的目的是寻找一个最佳的股票买卖时机,使得获得的利润最大化。 - 问题分析:此题是一道典型的动态规划问题,也可以使用贪心算法解决。 - 解题思路:贪心算法...
在探讨python实现leetcode第122题"Best Time to Buy and Sell Stock II"的解决方案前,我们首先需要明确题目要求。第122题属于动态规划和贪心算法范畴,要求编写一个程序,通过分析给定的股票价格数组来找出最大的...
Best Time to Buy and Sell Stock I是LeetCode网站上的一道著名的编程题目,它属于动态规划的范畴。这道题目通常被称为“买卖股票的最佳时机”,主要是考察程序员对动态规划思想的理解和应用。在这个问题中,给定一...
在探讨如何用Python解决LeetCode上的第121题“最佳买卖股票时机”之前,我们有必要对相关概念和解决策略进行充分了解。本题要求找到只进行一次买卖的最大利润,是动态规划算法中的典型问题。 首先,我们要明确题目...
在JavaScript的世界里,LeetCode是一个广受欢迎的在线编程平台,它提供了一系列的算法题目,帮助程序员提升编程技能。其中“121. 买卖股票的最佳时机”是一个经典的动态规划问题,经常作为算法入门的练习题。本题...
在JavaScript(简称JS)编程中,LeetCode题库提供了一系列的编程挑战,旨在帮助开发者提升算法和编程能力。本篇文档将深入分析LeetCode 122号题目,即“买卖股票的最佳时机 II”,并给出一种JS语言的解决方案。此...
leetcode-java leetcode刷题笔记 已做题目列表 1.Two Sum 3.Longest Substring Without Repeating Characters 5.Longest Palindromic Substring 20.Valid Parentheses 26.Remove Duplicates from Sorted Array 53....
LeetCode,作为全球知名的在线编程挑战平台,为学习和实践算法提供了丰富的资源,其上的“leetcode-spider”项目则为程序员提供了一个自动爬取和练习LeetCode算法题目的工具。 一、算法概述 算法,简单来说,就是...
《使用leetcode-editor在IDE中进行LeetCode练习的全方位指南》 LeetCode是一个广受欢迎的在线编程练习平台,它提供了一系列的算法题目供程序员们提升技能。对于习惯在集成开发环境(IDE)中工作的开发者来说,将...
java java_leetcode-114-flatten-binary-tree-to-linked-list
java java_leetcode-105-construct-binary-tree-from-preorder-and-inorde
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...