每日刷题:122. 买卖股票的最佳时机 II

167 阅读1分钟

难度:简单

给定一个数组 prices ,其中 prices[i] 是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

解题思路

低买高卖

题解

public int maxProfit(int[] prices) {
    int earn = 0;
    for (int index = 1, length = prices.length; index < length; index++) {
        earn += Math.max(prices[index] - prices[index - 1], 0);
    }
    return earn;
}

测试

BestTimeToBuyAndSellStockII bestTimeToBuyAndSellStockII = new BestTimeToBuyAndSellStockII();

@Test
public void test_case1() {
    Assertions.assertEquals(7, bestTimeToBuyAndSellStockII.maxProfit(new int[]{7, 1, 5, 3, 6, 4}));
}

@Test
public void test_case2() {
    Assertions.assertEquals(4, bestTimeToBuyAndSellStockII.maxProfit(new int[]{1, 2, 3, 4, 5}));
}

@Test
public void test_case3() {
    Assertions.assertEquals(0, bestTimeToBuyAndSellStockII.maxProfit(new int[]{7, 6, 4, 3, 1}));
}