Today I have Solved the problem in javascript

 Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k.

const array = [10, 5, 2, 7, 8, 7];

const k = 3;

maxValuesOfSubarrays(array, k);

function maxValuesOfSubarrays(arr, k) {

  if (k > arr.length || k < 1) {

    console.log("Invalid input.");

    return; }

let maxValues = [];

  let maxIndex = -1;

for (let i = 0; i < arr.length - k + 1; i++) {

   if (maxIndex >= i && maxIndex < i + k) {

      maxValues.push(Math.max(arr[i + k - 1], arr[maxIndex]));

    if (arr[i + k - 1] > arr[maxIndex]) {

        maxIndex = i + k - 1;

      }

    } else {

      

      let max = -1;

      for (let j = i; j < i + k; j++) {

        if (arr[j] > max) {

          max = arr[j];

          maxIndex = j;

        }

      }

      maxValues.push(max);

    }

  }  console.log(maxValues);}





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