← All problems · Arrays & Searching
Maximum Difference Between Two Ordered Array Elements
Return the maximum a[j]-a[i] for i<j. A decreasing array may produce a negative result; return 0 if n<2.
Implement int64_t max_difference(const int32_t *a, 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.
Track the minimum value strictly before the current element.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
int64_t max_difference(const int32_t *a, size_t n)
{
if(n<2)return 0;
int32_t min=a[0]; int64_t best=(int64_t)a[1]-a[0];
for(size_t i=1;i<n;++i){
int64_t d=(int64_t)a[i]-min;
if(d>best)best=d;
if(a[i]<min)min=a[i];
}
return best;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
std::int64_t max_difference(const std::int32_t *a, std::size_t n)
{
if(n<2)return 0;
std::int32_t min=a[0]; std::int64_t best=(std::int64_t)a[1]-a[0];
for(std::size_t i=1;i<n;++i){
std::int64_t d=(std::int64_t)a[i]-min;
if(d>best)best=d;
if(a[i]<min)min=a[i];
}
return best;
}
Compare before updating the minimum to enforce i<j. Widen subtraction to avoid overflow for 32-bit inputs.
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[]={2,3,10,6,4,8,1}, b[]={5,3,2}, c[]={INT32_MIN,INT32_MAX};
CHECK(max_difference(a,7)==8);
CHECK(max_difference(b,3)==-1);
CHECK(max_difference(c,2)==4294967295LL);
CHECK(max_difference(NULL,0)==0);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}