Say you have an array for which the i th 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).多次买卖
思路一:贪心算法,每次比较相邻两次产生利润就卖出去,总利润为每次利润的和
public class Solution {
public int maxProfit(int[] prices) {
int maxprofit=0;
for(int i=1;i<prices.length;i++){
if(prices[i]>prices[i-1])
maxprofit+=(prices[i]-prices[i-1]);
}
return maxprofit;
}
}
题型二:
Say you have an array for which the i th element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
思路二:遍历,
(1)当前价格小于最小价格,当前为最小价格
(2)否则如果当前价格-最小价格>最大利润,将他们设为最大利润
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0)
return 0;
int maxprofit=0;
int minprice=prices[0];
for(int i=1;i<prices.length;i++){
if(prices[i]<minprice)
minprice=prices[i];
else if(prices[i]-minprice>maxprofit)
maxprofit=prices[i]-minprice;
}
return maxprofit;
}
}
题型三:
Say you have an array for which the i th 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.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
?思路:利用四个变量分布表示当前买卖后手中的money
public class Solution {
public int maxProfit(int[] prices) {
//初始化时buy1和buy2都给极小的负值,因为之后买-prices[i]统一表达,四个遍历分别表示第一次/第二次买卖时手中持有的最大值
int buy1=Integer.MIN_VALUE,sell1=0,buy2=Integer.MIN_VALUE,sell2=0;
for(int i=0;i<prices.length;i++){
buy1=Math.max(buy1,-prices[i]);
sell1=Math.max(sell1,buy1+prices[i]);
buy2=Math.max(buy2,sell1-prices[i]);
sell2=Math.max(sell2,buy2+prices[i]);
}
return sell2;
}
}
常规思路:
分成两次,做题型二的最大利润,然后找到分割点
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length<2)
return 0;
//从前遍历最大利润
int[] premaxprofit=new int[prices.length];
int[] lastmaxprofit=new int[prices.length];
int premin=prices[0];
premaxprofit[0]=0;
for(int i=1;i<prices.length;i++){
premaxprofit[i]=Math.max(premaxprofit[i-1],prices[i]-premin);
premin=Math.min(premin,prices[i]);
}
//反向从尾到头,从后遍历最大利润
lastmaxprofit[prices.length-1]=0;
int lastmax=prices[prices.length-1];
for(int i=prices.length-2;i>=0;i--){
lastmaxprofit[i]=Math.max(lastmaxprofit[i+1],lastmax-prices[i]);
lastmax=Math.max(lastmax,prices[i]);
}
//遍历分割点,找分割点,使前后两次利润最大
int res=lastmaxprofit[0];
for(int cutpoint=1;cutpoint<prices.length;cutpoint++)
res=Math.max(res,premaxprofit[cutpoint-1]+lastmaxprofit[cutpoint]);
return res;
}
}