📜  hackerrank min max sum 解决方案 - Javascript (1)

📅  最后修改于: 2023-12-03 15:01:05.971000             🧑  作者: Mango

Hackerrank Min Max Sum Solution - JavaScript

Introduction

Hackerrank is a popular online coding platform that allows programmers to solve coding challenges in various programming languages. The Min Max Sum problem is one of the challenges on the platform that requires the programmer to find the minimum and maximum sums of a given array of integers.

In this article, I will provide a JavaScript solution to the Hackerrank Min Max Sum problem. The solution is explained step by step and includes code snippets.

Problem Description

Given an array of integers, find the minimum and maximum sums that can be obtained by summing exactly four of the five integers in the array.

For example, given the array [1, 2, 3, 4, 5], we can get the following sums:

  • 1 + 2 + 3 + 4 = 10
  • 1 + 2 + 3 + 5 = 11
  • 1 + 2 + 4 + 5 = 12
  • 1 + 3 + 4 + 5 = 13
  • 2 + 3 + 4 + 5 = 14

The minimum sum is 10 and the maximum sum is 14.

Solution

To solve the Hackerrank Min Max Sum problem, we need to first sort the array in ascending order. We can then calculate the minimum sum by adding the first four elements of the array and the maximum sum by adding the last four elements of the array.

Here's how we can implement this solution in JavaScript:

function miniMaxSum(arr) {
  arr.sort((a, b) => a - b);
  let minSum = arr[0] + arr[1] + arr[2] + arr[3];
  let maxSum = arr[arr.length-1] + arr[arr.length-2] + arr[arr.length-3] + arr[arr.length-4];
  console.log(minSum, maxSum);
}

We first sort the array using the sort() method and a custom comparison function that sorts the elements in ascending order. We then calculate the minimum sum by adding the first four elements of the sorted array and the maximum sum by adding the last four elements of the sorted array.

Finally, we log the minimum and maximum sums to the console using the console.log() method.

Conclusion

In this article, we have seen how to solve the Hackerrank Min Max Sum problem using JavaScript. The solution is straightforward and involves sorting the array and calculating the minimum and maximum sums. By understanding the problem and implementing the solution step by step, we can improve our problem-solving skills and become better programmers.