`

Best Time to Buy and Sell Stock II

阅读更多
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).

与第一个股票问题的区别是这里我们可以进行多次交易,我们同样用两个变量,profit用来记录当前交易是否盈利,如果是盈利就加入到总利润max中,如果亏损就继续往下查找。这样只要能盈利的都会记录到max中,代码如下:
public class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        int max = 0;
        for(int i = 1; i < prices.length; i++) {
            profit = prices[i] - prices[i - 1];
            if(profit > 0) 
                max += profit;
        }
        return max;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics