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).
Array Greedy
方法一:Greedy(贪心算法)【if(a[i]<a[i+1]){num+=a[i+1]-a[i]}】
方法二:动规思想
public int maxProfit(int[] prices) {
int num=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i]<prices[i+1]){
num+=(prices[i+1]-prices[i]);
}
}
return num;
}
方法二:动规思想
public int maxProfit(int[] prices) {
int i=0,num=0;
boolean buy=false;
for(;i<prices.length-1;i++){
if(buy&&prices[i]>prices[i+1]){
num+=prices[i];
buy=false;
}
if(!buy&&prices[i]<prices[i+1]){
num-=prices[i];
buy=true;
}
}
if(buy){
num+=prices[i];
}
return num;
}