EN
TypeScript - find max value skipping n found max values
0 points
In this article, we would like to show how to find the n-th max number value in a number array using TypeScript.
The main idea in the presented solution is to use a special buffer array with candidates to store maximal detected number values and return only n-th maximal value from the buffer.
Using the below solution we are able to find:
- maximal value (1st max),
- second maximal value (2nd max),
- third maximal value (3rd max),
- and so on (n-th maximal value)
Practical example:
xxxxxxxxxx
1
const findIndex = (candidates: number[], number: number): number | null => {
2
for (let j = 0; j < candidates.length; ++j) {
3
const candidate = candidates[j];
4
if (number > candidate) {
5
return j;
6
}
7
}
8
return null;
9
};
10
11
const findMax = (numbers: number[], skip: number = 0): number | null => {
12
const limit = skip + 1;
13
if (limit > numbers.length) {
14
return null;
15
}
16
const candidates = [] as number[];
17
for (let i = 0; i < limit; ++i) {
18
const number = numbers[i];
19
const index = findIndex(candidates, number);
20
candidates.splice(index ?? candidates.length, 0, number);
21
}
22
for (let i = limit; i < numbers.length; ++i) {
23
const number = numbers[i];
24
const index = findIndex(candidates, number);
25
if (index != null) {
26
candidates.splice(index, 0, number);
27
candidates.pop();
28
}
29
}
30
return candidates[skip];
31
};
32
33
34
// Usage example:
35
36
const numbers: number[] = [2, 4, 3, 1];
37
38
console.log(findMax(numbers)); // 4 // normal max value searching
39
console.log(findMax(numbers, 1)); // 3 // max value searching with skipping 1 max value
40
console.log(findMax(numbers, 2)); // 2 // max value searching with skipping 2 max values
41
console.log(findMax(numbers, 3)); // 1 // max value searching with skipping 3 max values
42
console.log(findMax(numbers, 4)); // null // we are not able to skip 4 max values because of numbers array length
Output:
xxxxxxxxxx
1
4
2
3
3
2
4
1
5
null