买卖股票的最佳时机II

问题描述: 

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

思路: 我的解题思路是先找出买入股票的那一天,然后找到卖出股票的那一天,接着重复这个过程。

解法一:

public static int maxProfit(int[] prices) {
		if(prices == null || prices.length <= 1)
			return 0;
		int buy = -1;
		int maxProfix = 0;
		for(int i = 0; i<prices.length-1;){
			if(prices[i] < prices[i+1]){ // 找到买入股票的那一天
				buy = i;
			}else{
				i++;
				continue;
			}
			if(buy == -1) // 没有找到直接返回
				return maxProfix;
			for(int j = buy+1; j<prices.length; j++){ // 寻找卖出股票的时机
				if(j == (prices.length-1)){ // 最后一天
					maxProfix += (prices[j] - prices[buy]);
					i = j; // 跳出外循环
					break;
				}
				if(prices[j+1] < prices[j]){ 
					int tmp = prices[j] - prices[buy];
					maxProfix += tmp;
					i = (j+1); // 重新定位买入股票的时机
					break;
				}
			}
		}
		return maxProfix;
	}

解法二:

精简后的代码如下:

public static int maxProfit2(int[] prices) {
		int profit = 0;
		int i = 0;
		while(i<prices.length-1){
			while(i<prices.length-1 && prices[i] >= prices[i+1]) i++;
			int buyPrice = prices[i];
			while(i<prices.length-1 && prices[i+1] >= prices[i]) i++;
			profit += prices[i] - buyPrice;
		}
		return profit;
	}

解法三:

看了下别人的代码,大体思路也是找出买入的天数和卖出的天数,不过是用递归实现的:

public static int maxProfit3(int[] prices) {
		return maxProfitRec(prices,0);
	}
	private static int maxProfitRec(int[] prices, int start){
		int last = prices.length - 1;
		while((start < last) && (prices[start] >= prices[start+1])){
			start++; // 买入
		}
		int end = start;
		while((end < last) && (prices[end] < prices[end+1])){
			end++; // 卖出
		}
		if(start == end)
			return 0;
		int profit = prices[end] - prices[start];
		return profit + maxProfitRec(prices, end);
	}

解法四:

也可以遍历数组,一发现前后两天有利益就进行买入卖出,这个其实是上一种思路的一种变体:

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;
    }

猜你喜欢

转载自blog.csdn.net/u014763678/article/details/83064463