Leetcode之动态规划(DP)专题-121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)...
2019-09-08 18:28
363 查看
原文链接:http://www.cnblogs.com/qinyuguan/p/11487741.html
Leetcode之动态规划(DP)专题-121. 买卖股票的最佳时机(Best Time to Buy and Sell Stock)
股票问题:
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1] 输出: 0 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
这题只需要两个for循环,找到两个数,差值最大且差值>0就ok。
用dp做:
dp[i][j][k]表示在第i天,我有j支股票,最大限制交易k次
这题里k=1 j=0或者1
详解看 有交易费的股票问题。
class Solution { public int maxProfit(int[] prices) { if(prices==null || prices.length == 0) return 0; int k = 1; int[][][] dp = new int[prices.length][2][k+1]; dp[0][0][0] = 0; dp[0][1][1] = -prices[0]; for (int i = 1; i < prices.length; i++) { dp[i][0][k] = Math.max(dp[i-1][1][k]+prices[i],dp[i-1][0][k]); dp[i][1][k] = Math.max(dp[i-1][0][k-1]-prices[i],dp[i-1][1][k]); } return dp[prices.length-1][0][k]; } }
转载于:https://www.cnblogs.com/qinyuguan/p/11487741.html
相关文章推荐
- [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机
- [Leetcode] Best time to buy and sell stock ii 买卖股票的最佳时机
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- [Java语言] [Leetcode] Best Time to Buy and Sell Stock 买卖股票的最佳时机
- Leetcode121 Best Time to Buy and Sell Stock(买卖股票的最佳时机1)
- [Leetcode] Best time to buy and sell stock 买卖股票的最佳时机
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- [LeetCode 121] - 买入与卖出股票的最佳时机(Best Time to Buy and Sell Stock)
- leetcode 121.Best Time to Buy and Sell Stock 股票买卖最佳时间
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- [LeetCode 123] - 买入与卖出股票的最佳时机III(Best Time to Buy and Sell Stock III)
- LeetCode——Best Time to Buy and Sell Stock I (股票买卖时机问题1)
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- 【LintCode】 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III
- [LeetCode] 121. Best Time to Buy and Sell Stock 买卖股票的最佳时间
- LeetCode 121. Best Time to Buy and Sell Stock (买卖股票的最好时机)
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- 【LintCode】 Best Time to Buy and Sell Stock 买卖股票的最佳时机
- LeetCode——Best Time to Buy and Sell Stock II (股票买卖时机问题2)
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode