Best Time to Buy and Sell Stock II

来源:互联网 发布:银联快捷支付 网络支付 编辑:程序博客网 时间:2024/05/01 12:35

题目原型:

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).

基本思路:

在题1的基础上,这个题是说可以交易多次。所以我们在保证即将减的情况下卖出,即将升的情况下买入。

public int maxProfit(int[] prices){if(prices==null||prices.length==0)return 0;int maxProfit = 0;int count = 0;for(int i = prices.length-1;i>0;i--){if(count>=0){if(count<=count+(prices[i]-prices[i-1]))count+=(prices[i]-prices[i-1]);else{maxProfit+=count;//卖出count = 0;}}else{count = (prices[i]-prices[i-1])>0?(prices[i]-prices[i-1]):0;}}if(count>0)maxProfit+=count;return maxProfit;}


 

 

0 0
原创粉丝点击