标签:
Best Time to Buy and Sell Stock III
问题:
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) { if(prices == null || prices.length <= 1) return 0; int size = prices.length; int[] left = new int[size]; int[] right = new int[size]; int min = prices[0]; int max = prices[size-1]; int rst = 0; for(int i=1; i<size; i++) { min = Math.min(min,prices[i]); left[i] = Math.max(left[i-1],prices[i]-min); } for(int j=size-2; j>=0; j--) { max = Math.max(max,prices[j]); right[j] = Math.max(right[j+1],max-prices[j]); } for(int k=0; k<size; k++) { rst = Math.max(rst, left[k]+right[k]); } return rst; } }
学习之处:
Best Time to Buy and Sell Stock III
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4461299.html