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){
return 0;
}
int profit = 0;
int buy = prices[0];
int sell = prices[0];
profit = sell - buy;
int flag = 0;
for(int i = 1 ; i < prices.length; i ++){
if(prices[i] > prices[i - 1]){//升序
sell = prices[i];//升序的过程中一直更新sell价格
flag = 1;
}else{
profit += sell - buy;
sell = prices[i];
buy = prices[i];
flag = 0;
}
}
if(flag == 1){//最后一个阶段一直升序,没有降序
profit += sell - buy;
}
return profit;
}
}
跟
Best Time to Buy and Sell Stock相比,可以进行多次交易,那么什么时候进行交易利益会最大化呢,观察发现,低价格买进,高价格卖出,而这期间价格一直在上升,这些时间段是最好的交期时间
故也就是要从一个数组中找出所有的升序序列,然后将这些升序序列的最大值和最小值的差值之和。
Runtime: 230 ms