leetcode之Best Time to Buy and Sell Stock II

来源:互联网 发布:传奇霸业胸章属性数据 编辑:程序博客网 时间:2024/04/28 04:22

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 == null || prices.length <= 1)              return 0;         int max = 0;        int begin = 0,end = 0;        for(int i = 1; i < prices.length; i ++){            if(prices[end] > prices[i]){                max += maxProfitByOneTransaction(prices, begin, end);                begin = end + 1;                end = end + 1;            }else{                end ++;            }        }        if(end != begin)            max += maxProfitByOneTransaction(prices, begin, end);        return max;    }        public int maxProfitByOneTransaction(int[] prices, int begin, int end) {          if(prices == null || prices.length <= 1)              return 0;          int maxProfit = 0;          int maxValue = prices[begin], minValue = prices[begin];          for(int i = begin + 1; i <= end; i ++){              if(maxValue < prices[i]){                  maxValue = prices[i];              }else if(minValue > prices[i]){                  minValue = prices[i];                  maxValue = prices[i];              }                            if(maxProfit < maxValue - minValue){                  maxProfit = maxValue - minValue;              }                        }          return maxProfit;      }  }


0 0