Skip to content

Instantly share code, notes, and snippets.

@klopp
Last active October 8, 2020 18:50
Show Gist options
  • Save klopp/7c2257573bb8cac31c5cbbf7ff34e012 to your computer and use it in GitHub Desktop.
Save klopp/7c2257573bb8cac31c5cbbf7ff34e012 to your computer and use it in GitHub Desktop.
Максимальная сумма непрерывной возрастающей последовательности в массиве, O(n)
#include <stdio.h>
#define TEST_MAX_SUM_OF_INC_SUBSEC_(a, ok) \
errors += test_( (a), sizeof((a)) / sizeof((a)[0]), (ok) )
static long max_sum_of_inc_subseq_( const int *array, size_t size )
{
long sum_max = 0;
if( array ) {
sum_max = array[0];
if( size > 1 ) {
long sum_current = array[0];
size_t i = 1;
do {
if( array[i - 1] < array[i] ) {
/* here you need to track the overflow! */
sum_current += array[i++];
}
else {
if( sum_max < sum_current )
sum_max = sum_current;
sum_current = array[i++];
}
} while( i < size );
if( sum_max < sum_current )
sum_max = sum_current;
}
}
return sum_max;
}
static int test_( const int *array, size_t size, long want )
{
long got = max_sum_of_inc_subseq_( array, size );
printf( "Want %4ld, got %4ld : %s.\n", want, got, got == want ? "OK" : "ERROR" );
return got != want;
}
int main( void )
{
int errors = 0;
static const int a[] = { 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11 };
static const int b[] = { 1, 101, 2, 3, 100, 4, 5 };
static const int c[] = { 9, 15, 11, 3, 48, 12, 10 };
static const int d[] = { 2, -75, 29, 91, -29, 53 };
static const int e[] = { 65, 48, 22, 82, 59 };
static const int f[] = { 30, -8, 56, 15 };
static const int g[] = { 37, 56, 70, 41, 33, 38, 55, 73 };
static const int h[] = { -62, -66, -62, -9, -80, -56, -87, -11, -41, -57 };
TEST_MAX_SUM_OF_INC_SUBSEC_( a, 20 ); /* [6, 14] */
TEST_MAX_SUM_OF_INC_SUBSEC_( b, 105 ); /* [2, 3, 100] */
TEST_MAX_SUM_OF_INC_SUBSEC_( c, 51 ); /* [3, 48] */
TEST_MAX_SUM_OF_INC_SUBSEC_( d, 45 ); /* [-75, 29, 91] */
TEST_MAX_SUM_OF_INC_SUBSEC_( e, 104 ); /* [22, 82] */
TEST_MAX_SUM_OF_INC_SUBSEC_( f, 48 ); /* [-8, 56] */
TEST_MAX_SUM_OF_INC_SUBSEC_( g, 199 ); /* [33, 38, 55, 73] */
TEST_MAX_SUM_OF_INC_SUBSEC_( h, -41 ); /* [-41] */
return errors;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment