Longest Two-Type Subarray
JavaScript
Medium
4 views
Problem Description
Given an array, find the longest contiguous subarray that contains at most 2 distinct numbers. Print its length.
Input Format
One line: n then n integers.
Output Format
One integer length.
Official Solution
const fs=require('fs');const a=fs.readFileSync(0,'utf8').trim().split(/\\s+/);if(!a[0])process.exit(0);let i=0;const n=Number(a[i++]);let arr=new Array(n);for(let j=0;j<n;j++)arr[j]=a[i++];let l=0;const cnt=new Map();let best=0;for(let r=0;r<n;r++){cnt.set(arr[r],(cnt.get(arr[r])||0)+1);while(cnt.size>2){const v=arr[l++];cnt.set(v,cnt.get(v)-1);if(cnt.get(v)===0)cnt.delete(v);}const len=r-l+1;if(len>best)best=len;}process.stdout.write(String(best));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!