</>EmbeddedInterview
← All problems · Arrays & Searching

Stock Buy and Sell for Maximum Profit (Multiple Transactions)

Easy

Given nonnegative daily prices, find the maximum profit with unlimited transactions, at most one share held at a time, and no fees. Assume the answer fits int64_t. Implement int64_t max_profit(const int32_t *prices, size_t n).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Add every positive increase between consecutive days.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>

int64_t max_profit(const int32_t *prices, size_t n)
{
    int64_t profit=0;
    for(size_t i=1;i<n;++i)if(prices[i]>prices[i-1])profit+=(int64_t)prices[i]-prices[i-1];
    return profit;
}

Consecutive rises can be combined into a single buy/sell transaction. Declines contribute no profit.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    int32_t a[]={1,5,3,1,2,8}, b[]={5,3,1}, c[]={1,3,5};
    CHECK(max_profit(a,6)==11);
    CHECK(max_profit(b,3)==0);
    CHECK(max_profit(c,3)==4);
    CHECK(max_profit(NULL,0)==0);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}