Languages
[Edit]
EN

TypeScript - find max value skipping n found max values

0 points
Created by:
Dollie-Rutledge
806

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:

const findIndex = (candidates: number[], number: number): number | null => {
    for (let j = 0; j < candidates.length; ++j) {
        const candidate = candidates[j];
        if (number > candidate) {
            return j;
        }
    }
    return null;
};

const findMax = (numbers: number[], skip: number = 0): number | null => {
    const limit = skip + 1;
    if (limit > numbers.length) {
        return null;
    }
    const candidates = [] as number[];
    for (let i = 0; i < limit; ++i) {
        const number = numbers[i];
        const index = findIndex(candidates, number);
        candidates.splice(index ?? candidates.length, 0, number);
    }
    for (let i = limit; i < numbers.length; ++i) {
        const number = numbers[i];
        const index = findIndex(candidates, number);
        if (index != null) {
            candidates.splice(index, 0, number);
            candidates.pop();
        }
    }
    return candidates[skip];
};


// Usage example:

const numbers: number[] = [2, 4, 3, 1];

console.log(findMax(numbers));    // 4      // normal max value searching
console.log(findMax(numbers, 1)); // 3      // max value searching with skipping 1 max value
console.log(findMax(numbers, 2)); // 2      // max value searching with skipping 2 max values
console.log(findMax(numbers, 3)); // 1      // max value searching with skipping 3 max values
console.log(findMax(numbers, 4)); // null   // we are not able to skip 4 max values because of numbers array length

Output:

4
3
2
1
null

 

See also

  1. JavaScript - find max value skipping n found max values 

Alternative titles

  1. TypeScript - find n-th max number value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join