Finding maximum number from two arrays in JavaScript

We need to create a JavaScript function that takes two arrays of single-digit numbers and returns a new array representing the maximum possible number of a specified length. The function must preserve the relative order of elements from each original array.

Problem Statement

Given two arrays representing numbers and a target length num, we need to:

  • Select digits from both arrays to form the largest possible number

  • Maintain the relative order within each array

  • Return exactly num digits

Example Input and Output

const arr1 = [1, 3, 4, 5, 6];
const arr2 = [9, 1, 2, 5, 8, 3];
const num = 4;

// Expected output: [9, 8, 6, 3]

Algorithm Approach

The solution uses dynamic programming with memoization to find the optimal combination:

  1. For each position, find the maximum digit available from both arrays

  2. When digits are equal, recursively compare remaining possibilities

  3. Use memoization to avoid recalculating subproblems

Complete Solution

const arr1 = [1, 3, 4, 5, 6];
const arr2 = [9, 1, 2, 5, 8, 3];
const num = 4;

const maxArray = (arr1 = [], arr2 = [], num) => {
    const map = new Map();
    
    const match = (a, b, num) => {
        if (map.has(a + ',' + b + ',' + num)) {
            return map.get(a + ',' + b + ',' + num);
        }
        
        let output = [];
        
        while(num > 0) {
            let maxa = -Infinity;
            let maxai = 0;
            let maxb = -Infinity;
            let maxbi = 0;
            
            // Find maximum in arr1 within valid range
            for(let i = a; i < arr1.length && arr1.length + arr2.length - (i + b) >= num; i++) {
                if (arr1[i] > maxa) {
                    maxa = arr1[i];
                    maxai = i;
                }
            }
            
            // Find maximum in arr2 within valid range
            for(let i = b; i < arr2.length && arr1.length + arr2.length - (a + i) >= num; i++) {
                if (arr2[i] > maxb) {
                    maxb = arr2[i];
                    maxbi = i;
                }
            }
            
            if (maxa === maxb) {
                // When equal, compare remaining sequences
                output.push(maxa);
                let ca = map.get(a+','+(maxbi+1)+','+(num-1)) || match(a, maxbi+1, num-1);
                let cb = map.get((maxai+1)+','+b+','+(num-1)) || match(maxai+1, b, num-1);
                
                map.set(a+','+(maxbi+1)+','+(num-1), ca);
                map.set((maxai+1)+','+b+','+(num-1), cb);
                
                if (ca.join('') > cb.join('')) {
                    return [...output, ...ca];
                } else {
                    return [...output, ...cb];
                }
            } else if (maxa > maxb) {
                output.push(maxa);
                a = maxai + 1;
            } else {
                output.push(maxb);
                b = maxbi + 1;
            }
            num--;
        }
        
        map.set(a + ',' + b + ',' + num, output);
        return output;
    };
    
    return match(0, 0, num);
};

console.log(maxArray(arr1, arr2, num));
[ 9, 8, 6, 3 ]

How It Works

  1. Range Validation: The condition arr1.length + arr2.length - (i + b) >= num ensures we have enough remaining elements

  2. Maximum Finding: We scan both arrays to find the largest available digit at each step

  3. Tie Breaking: When digits are equal, we recursively compare the remaining sequences and choose the lexicographically larger one

  4. Memoization: Results are cached using array positions and remaining count as keys

Key Points

  • Preserves relative order within each original array

  • Uses dynamic programming for optimal substructure

  • Handles edge cases where maximum digits are equal

  • Time complexity is optimized through memoization

Conclusion

This algorithm efficiently finds the maximum number by combining elements from two arrays while maintaining their relative order. The memoization approach ensures optimal performance for overlapping subproblems.

Updated on: 2026-03-15T23:19:00+05:30

705 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements