买卖股票的最好时机

题目:

链接:https://www.nowcoder.com/questionTerminal/572903b1edbd4a33b2716f7649b4ffd4
来源:牛客网

假设你有一个数组,其中第i个元素表示某只股票在第i天的价格。
设计一个算法来寻找最大的利润。你可以完成任意数量的交易(例如,多次购买和出售股票的一股)。但是,你不能同时进行多个交易(即,你必须在再次购买之前卖出之前买的股票)。

思路:

只要数组是递增的,就计算差值

代码:

 private static int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0){
            return 0;
        }
        int result = 0;
        for (int i = 1; i < prices.length; i++) {
                if(prices[i] > prices[i - 1]){
                    result += prices[i] - prices[i - 1];
                }
        }
        return result;
    }
原文地址:https://www.cnblogs.com/dongma/p/14197999.html