links: Algorithms MOC
Get Maximum in Generated Array
Problem:
You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way:
nums[0] = 0nums[1] = 1nums[2 * i] = nums[i]when2 <= 2 * i <= nnums[2 * i + 1] = nums[i] + nums[i + 1]when2 <= 2 * i + 1 <= n
Return the maximum integer in the array nums
Constraints:
0 <= n <= 100
Thought Process:
- You just have to loop through half of the n to generate the array, because
nums[i] = nums[2 * i]which meansnums[n] = nums[n / 2] - You will reach the end solution by solving smaller problems which is dynamic programming (if the n is 100, you have to calculate the indices before something like how fibonacci is solved)
- Consider the edge case when n is 0
/**
* @param {number} n
* @return {number}
*/
var getMaximumGenerated = function(n) {
if(n === 0) {
return 0
}
let array = new Array(n)
array[0] = 0;
array[1] = 1;
let result = Math.max(...n)
// loop length will be half of array and if it's odd add 1
// you can even use ceil
let loopLength = Math.floor(n / 2) + n % 2
for(let i = 0; i < loopLength; i++) {
array[2 * i] = array[i]
array[(2 * i) + 1] = array[i] + array[i + 1]
}
return Math.max(...array)
};tags: array dynamic-programming simulation
sources: