Second Largest (Distinct)
JavaScript
Easy
4 views
Problem Description
Find the second largest distinct value in the array. If it does not exist, print -1.
Input Format
One line: n then n integers.
Output Format
One integer answer.
Official Solution
const fs=require('fs');const p=fs.readFileSync(0,'utf8').trim().split(/\\s+/);if(!p[0])process.exit(0);let i=0;const n=Number(p[i++]);let first=-Infinity,second=-Infinity;for(let j=0;j<n;j++){const v=Number(p[i++]);if(v>first){second=first;first=v;}else if(v<first && v>second){second=v;}}process.stdout.write(second===-Infinity?'-1':String(second));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!