Find Max Slice Of Array | JavaScript


Let’s say, we are required to write a function that takes an array as input and returns the maximum slice of the array which contains no more than two different numbers. If we closely examine this problem this involves checking for a stable sub array and iterating over the original array.

Therefore, the sliding window algorithm is very suitable for this. The code for solving this problem via sliding window algorithm will be −

Example

const arr = [1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8, 1, 1 ,1 ,1, 8, 1,
1, 8, 8];
const map = {
   length: 0
};
let required = [];
for(start = 0, end = 0; end <= arr.length; ){
   if(map.length > 2){
      if(map[arr[start]] === 1){
         delete map[arr[start]];
         map.length --;
      }else{
         map[arr[start]]--;
      };
      start++;
      }else{
      if(end - start > required.length){
         required = arr.slice(start, end);
      };
      if(map[arr[end]]){
         map[arr[end]]++;
      }else{
         map[arr[end]] = 1;
         map.length++;
      }
      end++;
   }
}
console.log(required);

We maintained a map for storing the count of distinct characters at any point in the array and kept comparing the length of the longest subarray at each iteration, when the count of distinct characters exceeded 2, we slid the array towards right searching for the next stable array.

Output

The output in the console will be −

[
   1, 8, 1, 1, 1,
   1, 8, 1, 1, 8,
   8
]

Updated on: 20-Aug-2020

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements