一、 Best Time to Buy and Sell Stock II
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
eg:尽可能多的交易来保证利润最大
Q:you must sell the stock before you buy again?
我的理解就是当天同一时间不能卖完再买! 这样可以省掉许多的加法操作。
Example:
1 3 5 6 返回 0 +(6-1)而不是 0 + 3-1 + 5-3 + 6-5(当天卖完又可以买)实际上结果是没有变化的
1 2 3 1 5 返回 3-1 + 5 -1。 当前不能同一时间买卖。
我的理解:
不能在同一天卖出和买入,意思是下次购买前,你必须全部卖出你手上的股票。
1 2 3 :如果1买入,2卖出则不能再2买入,3抛出了,会损失一个利润点。正确的是1买入,3卖出。
另一种考虑:其实只要后面的大于前面的就可以买卖了,典型的贪婪算法。
(其实这两种算法都能AC = = !!! )
public static int maxProfit(int[] prices){
// 贪婪方法,如果不允许同一天买卖的话,那么就不能应用
int total = 0;
for(int i = 0; i < prices.length - 1; i ++){
if(prices[i + 1] > prices[i]) total += prices[i+1] - prices[i];
}
return total;
}
public static int maxProfit(int[] prices){
//不用贪婪,当两者结果是一样的
int profit = 0, i = 0;
while(i < prices.length){
//找局部最小值
while(i < prices.length - 1 && prices[i + 1] <= prices[i]) i++;
//找到了就开始下一个
int min = prices[i++];
//找写一个局部最大值
while(i < prices.length - 1 && prices[i + 1] >= prices[i]) i++;
profit = profit + (i < prices.length ? prices[i++] - min : 0);
}
return profit;
}