Difficulty: Easy

Given an array prices, prices[I] is the price of a given stock on day I.

Design an algorithm to calculate the maximum profit you can make. You can make as many trades (buying and selling a stock multiple times) as possible.

Note: You can’t participate in more than one transaction at a time (you must sell your previous shares before buying again).

Their thinking

Buy low sell high

Answer key

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;
}
Copy the code

test

BestTimeToBuyAndSellStockII bestTimeToBuyAndSellStockII = new BestTimeToBuyAndSellStockII();

@Test
public void test_case1(a) {
    Assertions.assertEquals(7, bestTimeToBuyAndSellStockII.maxProfit(new int[] {7.1.5.3.6.4}));
}

@Test
public void test_case2(a) {
    Assertions.assertEquals(4, bestTimeToBuyAndSellStockII.maxProfit(new int[] {1.2.3.4.5}));
}

@Test
public void test_case3(a) {
    Assertions.assertEquals(0, bestTimeToBuyAndSellStockII.maxProfit(new int[] {7.6.4.3.1}));
}
Copy the code