Consider that the greatest difference of the following 2 sets exceeds the int
range. For a more robust solution, return a wider type or detect failure.
{INT_MIN, INT_MAX}
{INT_MAX, INT_MIN}
// int custom_max(int n, int const* list)
long long custom_max(int n, int const* list)
Better to use size_t
for array indexing. int
may be too narrow.
A solution in liner time, as answered by @janos, is do-able, yet a few changes are needed to handle an ever decreasing list like {10,8,7,4,0}
.
For each element arr[i]
from 1 to n-1
, find if the difference of that element and the prior minimum is a greater difference.
Then update the minimum.
// Detect rare cases when long long and int have similar ranges.
#include <limits.h>
#if LLONG_MIN/2 > INT_MIN || LLONG_MAX/2 < INT_MIN
#error Need wider type
#endif
long long custom_max(size_t n, int const* list) {
if (n < 2) {
// Handle pathological case.
// Avoid magic number
// return 0x80000000;
return LLONG_MIN;
}
int min = list[0];
long long maxdiff = LLONG_MIN;
for (size_t i = 1; i < n; i++) {
long long diff = (long long) arr[i]list[i] - min;
if (diff > maxdiff) {
maxdiff = diff;
}
if (arr[i]list[i] < min) {
min = arr[i];list[i];
}
}
return maxdiff;
}