Home > Software design >  How to sum up all elements of the array if its strictly ascending?
How to sum up all elements of the array if its strictly ascending?

Time:10-08

the application prints the largest sum of a strictly ascending sequence of the array. A strictly ascending sequence is a sequence where the current number is always lesser than the next number.

For example, the user enters 2 4 5 1 7 3, the output should be 11 (2 4 5). I've passed all my test case except for one. Enter the size: 5 Enter element #1: 2 Enter element #2: 3 Enter element #3: 10 Enter element #4: 4 Enter element #5: 5 Largest sum = 24

The sum here should be 15.


int main(){

    int size;
    int sum = 0;
    int max;

    printf("Enter the size: ");
    scanf("%d", &size);
    int arr[size];

    for(int i = 0;i<size;i  ){
        printf("Enter element #%d: ",i 1);
        scanf("%d", &arr[i]);
    }

    for(int i = 0;i<size;i  ){

        max = arr[0];
        if(max<arr[i]){
        max = arr[i];
        }
        if(max>arr[i]){
            break;
        }
        sum = sum   arr[i];
    }
    printf("Largest sum = %d", sum);
}```

CodePudding user response:

max = arr[0]; should be outside the for loop:

max = arr[0];
for(int i = 0;i<size;i  ){
    if(max<arr[i]){
    max = arr[i];
    }
    if(max>arr[i]){
        break;
    }
    sum = sum   arr[i];
}

CodePudding user response:

This for loop

for(int i = 0;i<size;i  ){

    max = arr[0];
    if(max<arr[i]){
    max = arr[i];
    }
    if(max>arr[i]){
        break;
    }
    sum = sum   arr[i];
}

does not make a sense. For example the variable max is always set to the value of the first element of the array within each iteration of the loop

max = arr[0];

If I have understood correctly you need to find the maximum sum among sub-sequences of the array that are stored in the strictly ascending order.

If so then the approach can look for example the following way.

int calculated = 0;
long long int max_sum = 0;

for ( int i = 0; i < size; )
{
    long long int sum = a[i];

    while (   i != size && a[i-1] < a[i] ) sum  = a[i];

    if ( !calculated || max_sum < sum ) 
    {
        calculated = 1;
        max_sum = sum;
    }
}

if ( calculated ) printf( "Largest sum = %lld\n", max_sum );
  • Related