Today I have solved the problem in javascript

 Write a program to determine how many distinct ways there are to create a max heap from a list of N given integers.


For example, if N = 3, and our integers are [1, 2, 3], there are two ways, shown below.


  3      3

 / \    / \

1   2  2   1

const N = 3;

const result = countMaxHeapWays(N);

function nCr(n, r) {

    if (r === 0 || n === r) return 1;

    return nCr(n - 1, r - 1) + nCr(n - 1, r);

}


function leftChild(index) {

    return 2 * index + 1;

}


function calculateWays(n, dp) {

    if (n <= 1) {

        return 1;

    }


    if (dp[n] !== undefined) {

        return dp[n];

    }


    let leftSubtreeSize = 0;

    const height = Math.floor(Math.log2(n));

    const lastLevelNodes = n - Math.pow(2, height) + 1;


    if (lastLevelNodes >= Math.pow(2, height - 1)) {

        leftSubtreeSize = Math.pow(2, height) - 1;

    } else {

        leftSubtreeSize = Math.pow(2, height - 1) - 1 + lastLevelNodes;

    }


    dp[n] = (nCr(n - 1, leftSubtreeSize) * calculateWays(leftSubtreeSize, dp) * calculateWays(n - 1 - leftSubtreeSize, dp)) % (Math.pow(10, 9) + 7);


    return dp[n];

}


function countMaxHeapWays(N) {

    const dp = new Array(N + 1);

    return calculateWays(N, dp);

}



console.log(`There are ${result} distinct ways to create a max heap from a list of ${N} integers.`);

Output:

There are 2 distinct ways to create a max heap from a list of 3 integers.

Comments

Popular posts from this blog

Building a Full-Stack Student Management System with React.js and NestJS

Today I have solved the problem in javascript

Today I have solved problem in javascript