A 5ms C solution

  • 2

    This problem can be called "cumulative gain" instead. I hope this is clear enough.

    int maxProfit(int* prices, int pricesSize) {
        int cumulativeGain = 0;
        int lastVal = prices[0];
        for (int i = 1; i < pricesSize; i++) {
            if (prices[i] > lastVal) {
                cumulativeGain += prices[i] - lastVal;
            lastVal = prices[i];
        return cumulativeGain;

  • 0

    I have similar idea, start the loop from the end. But OJ says my code returns 2 for test case [1, 2].

    On my machine, it get the right answer 1. Haven't figure out what is wrong.

  • 0

    Is there any proof for this? It seems like a greedy strategy.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.