查找使用 JavaScript 对五个整数中的恰好四个进行求和可以计算出的最小值和最大值
给定一个包含五个正整数的数组,我们需要找到通过对这五个整数中的恰好四个进行求和可以计算出的最小值和最大值。
然后将相应的最小值和最大值作为两个用空格分隔的长整数打印在一行上。
数组并非始终排序。
例如 -
const arr = [1, 3, 5, 7, 9]
最小和为 -
1 + 3 + 5 + 7 = 16
最大和为 -
3 + 5 + 7 = 24
函数的返回值应为 -
[16, 24];
示例
代码如下 -
const arr = [1, 3, 5, 7, 9]
const findMinMaxSum = (arr = []) => {
let numbers = arr.slice().sort();
let maxScore = 0;
let minScore = 0;
for(let i = 0; i < numbers.length − 1; i++) {
minScore += numbers[i];
};
for(let j = 1; j < numbers.length; j++) {
maxScore += numbers[j];
};
return [minScore, maxScore];
};
console.log(findMinMaxSum(arr));输出
控制台中的输出将为 -
[16, 24]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP