股票买卖问题-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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值