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 two transactions.
public class Solution { public int maxProfit(int[] prices) { int res = 0; if (prices==null || prices.length<=1) { return 0; } int[] arrA = new int[prices.length]; int min = prices[0]; for (int i = 1; i < prices.length; i++) { min = Math.min(min, prices[i]); arrA[i] = Math.max(arrA[i-1], prices[i]-min); } int max = prices[prices.length-1]; int[] arrB = new int[prices.length]; for (int i = prices.length-2; i >= 0; i--) { max = Math.max(max, prices[i]); arrB[i] = Math.max(max-prices[i], arrB[i+1]); } for (int i = 0; i < prices.length; i++) { res = Math.max(res, arrA[i]+arrB[i]); } return res; } }
相关推荐
java java_leetcode题解之Best Time to Buy and Sell Stock III.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 IV.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刷题笔记 ...III 141.Linked List Cycle 142.Linked List Cycle II 188.Best Time to Buy and Sell Stock IV 217.Contains Duplicate 263.Ugly Number 264.Ugly Number II
- Best Time to Buy and Sell Stock III:存在多日限制交易,最多两次交易。 - Best Time to Buy and Sell Stock IV:与前三者不同,可能需要多次买入和卖出。 - Best Time to Buy and Sell Stock with Cooldown...
III (Hard) 最多两次交易(同理固定次数的多次),这种方法比较合理且避免了DP(好吧其实我不是很会DP) for i in prices: buy1 = min(buy1, i) #找当前最低一次买入价格 prof1 = max(prof1, i-buy1) #找第一次交易...
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题解之123_Best_Time_to_Buy_and_Sell_Stock_III
javascript js_leetcode题解之123-best-time-to-buy-and-sell-stock-iii.js
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题解之122_Best_Time_to_Buy_and_Sell_Stock_II
javascript js_leetcode题解之122-best-time-to-buy-and-sell-stock-ii.js
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 ...