How to find the two largest elements in an array with TypeScript

1 Answer

0 votes
/**
 * Finds the largest and second-largest elements in an array.
 */
interface TwoLargestResult {
    largest: number;
    secondLargest: number;
}

/**
 *
 * @param numbers Input array of numbers.
 * @returns An object containing the largest
 *          and second-largest elements.
 * @throws Error if the array contains fewer than two elements.
 */
function findTwoLargest(numbers: number[]): TwoLargestResult {
    if (numbers.length < 2) {
        throw new Error("Array must contain at least two elements.");
    }

    let largest: number = Number.NEGATIVE_INFINITY;
    let secondLargest: number = Number.NEGATIVE_INFINITY;

    for (const value of numbers) {
        // Found a new largest value
        if (value > largest) {
            secondLargest = largest;
            largest = value;
        }
        // Update second largest if needed
        else if (value > secondLargest) {
            secondLargest = value;
        }
    }

    return {
        largest,
        secondLargest
    };
}

/**
 * Program entry point.
 */
function main(): void {
    const numbers: number[] = [3, 4, 9, 6, 7, 1, 2, 5];

    const result: TwoLargestResult = findTwoLargest(numbers);

    console.log("Array:", numbers);
    console.log("Largest element:", result.largest);
    console.log("Second largest element:", result.secondLargest);
}

main();


/*
run:

Array: [
  3, 4, 9, 6,
  7, 1, 2, 5
]
Largest element: 9
Second largest element: 7

*/

 



answered 4 days ago by avibootz
...