122 Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II

假设有一个数组,它的第 i 个元素是一个给定的股票在第 i 天的价格。
设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。
详见:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/

Java实现:

方法一:

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

方法二:

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        if(n <= 1){
            return 0;
        }
        int i = 0;
        int profit = 0;
        while(i < n - 1){
            int buy,sell;
            //寻找递减区间的最后一个值(局部最小点)
            while(i+1 < n && prices[i+1] < prices[i]){
                ++i;
            }
            //局部最小点作为买入点
            buy = i;
            
            //找下一个点(卖出点至少为下一个点)
            ++i;
            //不满足。。继续往下找递增区间的最后一个值(局部最高点)
            while(i<n && prices[i] >= prices[i-1]){
                ++i;
            }
            //设置卖出点
            sell = i-1;
            //计算总和
            profit += prices[sell] - prices[buy];
        }
        return profit;
    }
}

参考:https://www.cnblogs.com/grandyang/p/4280803.html

原文地址:https://www.cnblogs.com/xidian2014/p/8722719.html