Mini-Max Sum

  • + 0 comments

    Python Solution

    The task is to find the minimum and maximum sum of four out of five elements in an array.

    Approach 1: Sorting The simplest way to solve this is by sorting the array. Once sorted, the minimum sum is the sum of the first four elements, and the maximum sum is the sum of the last four elements. This approach has a time complexity of 𝑂 ( 𝑛 log ⁡ 𝑛 ) O(nlogn) due to sorting.

    However, if it's guaranteed that the array will always be of length 5 (as is the case in this problem), then the time complexity doesn’t really matter, and sorting could be considered 𝑂 ( 1 ) O(1) because the size is constant.

    Approach 2: One Pass with Max and Min A more efficient way is to go through the array once ( 𝑂 ( 𝑛 ) O(n) time complexity), find the maximum and minimum values, and subtract them from the total sum of the array:

    The minimum sum is obtained by subtracting the maximum value from the total sum. The maximum sum is obtained by subtracting the minimum value from the total sum. Why Use This Approach? This method is more efficient because it avoids the sorting step, making it faster for larger arrays.

    Enjoy coding! If you have a better idea, please share!

    def miniMaxSum(arr): maximum, minimum = arr[0],arr[0] for i in range(len(arr)): maximum, minimum = max(maximum,arr[i]), min(minimum,arr[i])

    totSum = sum(arr)
    print(f"{totSum - maximum} {totSum - minimum}")
    

    if name == 'main':

    arr = list(map(int, input().rstrip().split()))
    
    miniMaxSum(arr)