Monday, 17 July 2017

find maximum and minimum sum of array in o(n)

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main() {
    int *arr = malloc(sizeof(int) * 5);
    long sum=0;
    for(int arr_i = 0; arr_i < 5; arr_i++){
       scanf("%d",&arr[arr_i]);
        sum= sum+arr[arr_i];
    }
    int max_i = 0;
    int min_i = 0;
    for (int arr_i=1;arr_i<5;arr_i++)
    {
        if (arr[arr_i]>arr[max_i])
        {
            max_i= arr_i ;
        }
        if (arr[arr_i]<arr[min_i])
        {
            min_i= arr_i;
        }       
    }
    printf("%ld %ld",sum-arr[max_i],sum-arr[min_i]);
    return 0;
}
 

No comments:

Post a Comment