We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Mini-Max Sum
- Discussions
Mini-Max Sum
Mini-Max Sum
Sort by
recency
|
971 Discussions
|
Please Login in order to post a comment
public static void miniMaxSum(List arr) { arr.Sort(); long min = arr[0], sum = 0, max = arr[arr.Count-1]; for(int i=0;i
O(n) solution get 4 numbers a circular ring like fashon and see if they are min or max sum.
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])
if name == 'main':
NodeJs/JavaScript: First, calculate the total sum of all elements in the array. Then, iterate through the array with reduce and determine the sum of four elements by subtracting each number from the total sum. Track the minimum and maximum sums during this process. Finally, print the smallest and largest sums obtained.