122.Best Time to Buy and Sell Stock II (Medium)

我的个人网站
点击可查看所有文章

这题的思想就是每天做交易
只要涨了就加入总盈利

输入: prices = [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
     随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
     
1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104
public int maxProfit(int[] prices) {
    
    
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
    
    
            int tmp = prices[i] - prices[i - 1];
            if (tmp > 0) profit += tmp;
        }
        return profit;
    }

猜你喜欢

转载自blog.csdn.net/qq_39644418/article/details/121950443