leetcode数组专项习题:股票买卖问题-II

3、买卖股票的最佳时间-II
best-time-to-buy-and-sell-stock-ii: Say you have an array for which the i th 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).
题目要求:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

分析:这是上一题的拓展版,在

https://blog.csdn.net/weixin_43277507/article/details/88092884

中,题目要求只能进行一次买卖,这其实降低了题目难度。在题二中,尽可能多的完成更多交易,可以对一支股票进行多次买卖。参考题一的解法,最直观的方法就是两次for循环,计算所有的可能性,选取总利润最大的组合。当然,这种解法的复杂度比较高。

public class Solution{
    public static void main(String[] args) {
    	Solution gupiao=new Solution();
    	int[] prices= {7,1,5,3,6,4};
    	int price=gupiao.maxProfit(prices);
    	System.out.println(price);
    }
    public int maxProfit(int[] prices) {
        int len=prices.length;
        int price=0;
        int num=0;
    	for(int i=num;i<len;i++)
    	{
    		
    		for(int j=i+1;j<len;j++)
    		{
    			if(prices[i]<prices[j])
    			{
    				price=price+prices[j]-prices[i];
    				num=j+1;
    			    
    		    }
                break;
    		}
    		
    	}
    	return price;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43277507/article/details/88093080
今日推荐