- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]