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.
public class Solution { public int maxProfit(int k, int[] prices) { if (prices == null || prices.length == 0) { return 0; } if (k > prices.length) { int res = 0; for (int i = 0; i < prices.length-1; i++) { int tmp = prices[i + 1] - prices[i]; if (tmp > 0) { res += tmp; } } return res; } int[][] global = new int[prices.length][k+1]; int[][] local = new int[prices.length][k+1]; for (int i = 0; i < prices.length-1; i++) { int tmp = prices[i + 1] - prices[i]; for (int j = 0; j < k; j++) { local[i+1][j+1] = Math.max(global[i][j]+Math.max(tmp,0), local[i][j+1] + tmp); global[i+1][j+1] = Math.max(global[i][j+1], local[i+1][j+1]); } } return global[prices.length-1][k]; } }
相关推荐
java java_leetcode题解之Best Time to Buy and Sell Stock IV.java
同时,我们需要一个变量`buy_price`来存储最近一次买入的价格,如果当前价格低于`buy_price`,我们就更新`buy_price`;如果当前价格高于`buy_price`,我们就计算利润并更新`max_profit`。 ### 算法流程 1. 初始化`...
java java_leetcode题解之Best Time to Buy and Sell Stock with Cooldown
java java_leetcode题解之Best Time to Buy and Sell Stock III.java
java java_leetcode题解之Best Time to Buy and Sell Stock II.java
java java_leetcode题解之Best Time to Buy and Sell Stock I.java
java lru leetcode leetcode-java leetcode刷题笔记 已做题目列表 1.Two Sum 3.Longest Substring ...121.Best Time to Buy and Sell ...IV 217.Contains Duplicate 263.Ugly Number 264.Ugly Number II
- Best Time to Buy and Sell Stock IV:与前三者不同,可能需要多次买入和卖出。 - Best Time to Buy and Sell Stock with Cooldown:买卖后需要冷却一天。 - Best Time to Buy and Sell Stock with Transaction...
Best Time to Buy and Sell Stock 122 买卖股票的最佳时机 Ⅱ Best Time to Buy and Sell StockⅡ 123 买卖股票的最佳时机 Ⅲ Best Time to Buy and Sell StockⅢ 188 买卖股票的最佳时机Ⅳ Best Time to Buy and ...
python python_leetcode题解121_Best_Time_to_Buy_and_Sell_Stock
javascript js_leetcode题解之121-best-time-to-buy-and-sell-stock.js
python python_leetcode题解之123_Best_Time_to_Buy_and_Sell_Stock_III
python python_leetcode题解之122_Best_Time_to_Buy_and_Sell_Stock_II
javascript js_leetcode题解之123-best-time-to-buy-and-sell-stock-iii.js
javascript js_leetcode题解之122-best-time-to-buy-and-sell-stock-ii.js
Best Time to Buy and Sell Stock (Easy) 一次交易,找最大收益 for i in prices: low = min(low, i) profit = max(profit, i-low) Best Time to Buy and Sell Stock II (Easy) 可多次交易,找总最大收益 for i in ...
63. 股票的最大利润题目链接Leetcode:121. Best Time to Buy and Sell Stock题目描述可以有一次买入和一次卖出,买入必
leetcode 分类 LeetCode LeetCode Java Solution 2018年5月31日 更新 最近刷了一遍 ...题,把相似的题目都放在了一起,比如Best Time to Buy and Sell Stock的6道题,这些题目放在一起刷效果更好。 简书博客:
Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate Reverse Polish Notation #169 Majority Element #171 Excel Sheet Column Number #217 Contains Duplicate #226 Invert Binary Tree #237 ...