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).
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0 || prices.length == 1){
return 0;
}
int max = 0;
int profit = prices[1] - prices[0] ;
int tmp = 0 ;
boolean flag = false ;
for(int i = 0 ; i<prices.length-1 ; i++ ){
if(prices[i+1] > prices[i]){
if(prices[tmp] > prices[i]){
tmp = i;
}
profit = prices[i+1] - prices[tmp];
flag = true;
}else{
if(flag){
max +=profit;
}
tmp=i+1;
flag = false;
}
}
if(flag){
max +=profit;
}
if(profit < 0){
return 0;
}
return max;
}
}
总结:感觉想麻烦了,一会看一下discuss,我的想法是,一个数组里找住最小的值,如果nums[ i+1 ]元素的值大于nums [ i ]的值,也就是说此时就应该把股票卖掉了,再重新记录最小值再循环比较即可。