[leetcode] 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).

https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

 

思路1:找出所有的递增序列,然后求和。

思路2:思路1稍微改进下,类似上题的diff[]数组,将其中所有的正数相加即可。

 

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null)
            return 0;
        int n = prices.length;
        int profit=0;
        for(int i=0;i<n-1;i++){
            if(prices[i+1]>=prices[i]){
                profit+=prices[i+1]-prices[i];
            }            
        }
        
        return profit;
    }
}

 

 

posted @ 2014-07-03 21:59  jdflyfly  阅读(138)  评论(0编辑  收藏  举报