Header Ad

HackerEarth Stevie problem solution

In this HackerEarth Stevie! problem solution You have been given 2 integer arrays A and B each of size N. Now we call a pair of indices (i,j) connected if i = j or A[i] = A[j].

Now, for each index i in the array A where 1 <= i <= N, you need to find the maximum B[j] such that indices i and j are connected. Can you do it ?


HackerEarth Stevie ! problem solution


HackerEarth Stevie! problem solution.

import java.io.*;
import java.util.*;
import java.math.*;

public final class solution
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static Random rnd=new Random();
static Map<Integer,Integer> m1=new HashMap<>();
static int max_val=(int)(1e9);

static void put(int idx,int val)
{
if(m1.get(idx)==null)
{
m1.put(idx,val);
}

else
{
m1.put(idx,Math.max(m1.get(idx),val));
}
}

public static void main(String args[]) throws Exception
{
int n=sc.nextInt();int[] a=new int[n],b=new int[n];

if(n<1 || n>200000) throw new Exception("Violation of Constraints");

for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();

if(a[i]<1 || a[i]>max_val) throw new Exception("Violation of Constraints");
}

for(int i=0;i<n;i++)
{
b[i]=sc.nextInt();

if(b[i]<1 || b[i]>max_val) throw new Exception("Violation of Constraints");

put(a[i],b[i]);
}

for(int i=0;i<n;i++)
{
out.print(m1.get(a[i])+" ");
}

out.println("");out.close();
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;

public FastScanner(BufferedReader in) {
this.in = in;
}

public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}

public String next() throws Exception {
return nextToken().toString();
}

public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}

public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}

public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
}


Second solution

#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
vector <int> A(n), B(n);
for (int i = 0; i < n; ++i)
{
cin>>A[i];
}
for (int i = 0; i < n; ++i)
{
cin>>B[i];
}
map <int,int> val;
for (int i = 0; i < n; ++i)
{
val[A[i]] = max(B[i], val[A[i]]);
}
for (int i = 0; i < n; ++i)
{
cout<<val[A[i]]<<" ";
}
return 0;
}

Post a Comment

0 Comments