leetcode (Best Time to Buy and Sell Stock II)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/84325925

Title: Merge Stored Array    122

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

这题时上一题121稍微的改变,因为不限制买卖,就可以表示在同一天可以以同样的价格买进卖出

1. 注意点见代码中的注释,时间&空间复杂度如下:

时间复杂度:O(n),一层for循环,需要遍历整个数组。

空间复杂度:O(1),没有申请额外的空间。

    /**
     * 注意的是同一天可以卖出买进(不限制买卖的次数)
     * @param prices
     * @return
     */
    public static int maxProfit(int[] prices) {

        if (prices == null || prices.length <= 1) {
            return 0;
        }

        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                maxProfit += prices[i] - prices[i - 1];
            }
        }

        return maxProfit;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/84325925