

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 ]
- Related Questions & Answers
- JavaScript Array slice()
- Array slice() in JavaScript
- Average of array excluding min max JavaScript
- How to find the min/max element of an Array in JavaScript?
- Top n max value from array of object JavaScript
- How to slice an array with wrapping in JavaScript
- Find max in struct array using C++.
- Array slice function in Ruby
- MongoDB Aggregation to slice array inside array
- Find max and min values in array of primitives using Java
- MongoDB slice array in populated field?
- MongoDB query to slice only one element of array
- Find max and min values in an array of primitives using Java
- what is the use of slice() method in JavaScript?
- Get max value per key in a JavaScript array
Advertisements