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

题目大意:

类似I,只不过现在允许进行多次交易,只需在上升曲线累加收益即可,即所谓的贪婪算法。

(贪婪算法与动态规划的区别:贪婪算法只需在每一步求出最大收益,即可在最后一步得到总的最大利润,而对于动态规划,每一步的最大收益可能受到前面某一步的影响,导致必须在最后一步综合前面的状态才能得出最大利润)

Java解法:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0)
            return 0;
        int profit = 0;
        int temp = prices[0];
        for(int i = 1; i<prices.length; i++){
            if(prices[i] > temp)   //上升曲线每步累加收益
                profit += prices[i] - temp;
            temp = prices[i];
        }
        return profit;
    }
}

 

你可能感兴趣的:(time)