Best Time to Buy and Sell Stock1,2,3,4

时间:2024-10-26 10:35:26

Best Time to Buy and Sell Stock1,2,3,4

找到最低值和最高值

int maxProfit(vector<int>& prices) {
if(prices.size()<)return ;
int profit=;
int cur_min=prices[];
for(int i=;i<prices.size();i++)
{
profit=max(profit,prices[i]-cur_min);//记录最大利润
cur_min=min(cur_min,prices[i]);//保留购买最小值
}
return profit;
}

2、Best Time to Buy and Sell Stock1,2,3,4

计算差分序列,大于0加入

int maxProfit(vector<int>& prices) {
if(prices.size()<)return ;
int profit=;
int diff=;
for(int i=;i<prices.size();i++)
{
diff=prices[i]-prices[i-];
if(diff>)profit+=diff;
}
return profit;
}

3、Best Time to Buy and Sell Stock1,2,3,4

把交易分成两次,分别完成,最后将利润相加求最大。

public int maxProfit(int[] prices) {
if (prices.length < ) return ; int n = prices.length;
int[] preProfit = new int[n];
int[] postProfit = new int[n]; int curMin = prices[];
for (int i = ; i < n; i++) {
curMin = Math.min(curMin, prices[i]);
preProfit[i] = Math.max(preProfit[i - ], prices[i] - curMin);
} int curMax = prices[n - ];
for (int i = n - ; i >= ; i--) {
curMax = Math.max(curMax, prices[i]);
postProfit[i] = Math.max(postProfit[i + ], curMax - prices[i]);
} int maxProfit = ;
for (int i = ; i < n; i++) {
maxProfit = Math.max(maxProfit, preProfit[i] + postProfit[i]);
} return maxProfit;
}

4、

Description: 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).

public int maxProfit(int k, int[] prices) {
if (prices.length < ) return ; int days = prices.length;
if (k >= days) return maxProfit2(prices); int[][] local = new int[days][k + ];
int[][] global = new int[days][k + ]; for (int i = ; i < days ; i++) {
int diff = prices[i] - prices[i - ]; for (int j = ; j <= k; j++) {
local[i][j] = Math.max(global[i - ][j - ], local[i - ][j] + diff);
global[i][j] = Math.max(global[i - ][j], local[i][j]);
}
} return global[days - ][k];
} public int maxProfit2(int[] prices) {
int maxProfit = ; for (int i = ; i < prices.length; i++) {
if (prices[i] > prices[i - ]) {
maxProfit += prices[i] - prices[i - ];
}
} return maxProfit;
}

参考:http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html

可以交易k次,没看懂,感觉自己好笨。。。