mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Added Mini-Max sum Algorithm
This commit is contained in:
parent
677146717d
commit
b5ca4b12e8
@ -71,6 +71,7 @@ a set of rules that precisely define a sequence of operations.
|
||||
* `B` [Pascal's Triangle](src/algorithms/math/pascal-triangle)
|
||||
* `B` [Complex Number](src/algorithms/math/complex-number) - complex numbers and basic operations with them
|
||||
* `B` [Radian & Degree](src/algorithms/math/radian) - radians to degree and backwards conversion
|
||||
* `B` [Mini-Max Sum](src/algorithms/math/mini-max-sum)
|
||||
* `B` [Fast Powering](src/algorithms/math/fast-powering)
|
||||
* `A` [Integer Partition](src/algorithms/math/integer-partition)
|
||||
* `A` [Square Root](src/algorithms/math/square-root) - Newton's method
|
||||
|
27
src/algorithms/math/mini-max/MiniMax.js
Normal file
27
src/algorithms/math/mini-max/MiniMax.js
Normal file
@ -0,0 +1,27 @@
|
||||
|
||||
/**
|
||||
*
|
||||
* @param numbers - array of numbers
|
||||
* @return [number - Max, number - Min]
|
||||
*/
|
||||
export default function miniMaxSum(numbers) {
|
||||
if (!Array.isArray(numbers) || numbers.length === 0) {
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
let min = numbers[0];
|
||||
let max = numbers[0];
|
||||
let sum = numbers[0];
|
||||
|
||||
for (let i = 1; i < numbers.length; i += 1) {
|
||||
sum += numbers[i];
|
||||
|
||||
if (numbers[i] > max) {
|
||||
max = numbers[i];
|
||||
} else if (numbers[i] < min) {
|
||||
min = numbers[i];
|
||||
}
|
||||
}
|
||||
|
||||
return [sum - max, sum - min];
|
||||
}
|
12
src/algorithms/math/mini-max/Readme.md
Normal file
12
src/algorithms/math/mini-max/Readme.md
Normal file
@ -0,0 +1,12 @@
|
||||
|
||||
# Mini-Max Sum
|
||||
|
||||
Given an array of five positive integers, find the minimum and maximum values that
|
||||
can be calculated by summing exactly four of the array integers. Then return the
|
||||
respective minimum and maximum values as a array of numbers
|
||||
|
||||
|
||||
```
|
||||
[1, 2, 3, 4, 5] = [10, 14]
|
||||
[1, 3, 5, 7, 9] = [16, 24]
|
||||
```
|
13
src/algorithms/math/mini-max/__test__/miniMax.test.js
Normal file
13
src/algorithms/math/mini-max/__test__/miniMax.test.js
Normal file
@ -0,0 +1,13 @@
|
||||
import miniMaxSum from '../miniMaxSum';
|
||||
|
||||
describe('miniMaxSum', () => {
|
||||
it('should calculate miniMaxSum', () => {
|
||||
expect(miniMaxSum([1, 3, 5, 7, 9])).toStrictEqual([16, 24]);
|
||||
expect(miniMaxSum([1, 2, 3, 4, 5])).toStrictEqual([10, 14]);
|
||||
expect(miniMaxSum([-1, -2, 3, 4, 5])).toStrictEqual([4, 11]);
|
||||
expect(miniMaxSum([0, 1, 2, 3, 4, 5])).toStrictEqual([10, 15]);
|
||||
expect(miniMaxSum([])).toStrictEqual([null, null]);
|
||||
expect(miniMaxSum(12)).toStrictEqual([null, null]);
|
||||
expect(miniMaxSum(null)).toStrictEqual([null, null]);
|
||||
});
|
||||
});
|
Loading…
Reference in New Issue
Block a user