Problem Statement:
Given an array of integers, find the nearest smaller number for every element such that the smaller element is on left side.If no small element present on the left print -1.
Input:
The first line of input contains T test cases.
The first line of each test case contains the number of elements in the array.
The second line of each test case contains the elements of the array.
Output:
Print the n elements.
Constraints:
1<=T<=100
1<=N<=100
0<=A[i]<10000
Example:
Input:
2
3
1 6 2
6
1 5 0 3 4 5
Output:
-1 1 1
-1 1 -1 0 3 4
import java.util.*;
import java.lang.*;
import java.io.*;
class MuscleJava
{
public static void print(int arr[], int n)
{
Stack st = new Stack();
for(int i=0; i {
// System.out.println("\n" + i);
while(!st.empty() && arr[i] <= st.peek() )
{
st.pop();
}
if(st.empty())
System.out.print("-1 ");
else
System.out.print(st.peek() + " ");
st.push(arr[i]);
}
}
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int k=0;k < t; k++)
{
int n = s.nextInt();
int arr[] = new int[n];
for(int i=0; i {
arr[i] = s.nextInt();
}
print(arr,n);
System.out.println();
}
}
}
Given an array of integers, find the nearest smaller number for every element such that the smaller element is on left side.If no small element present on the left print -1.
Input:
The first line of input contains T test cases.
The first line of each test case contains the number of elements in the array.
The second line of each test case contains the elements of the array.
Output:
Print the n elements.
Constraints:
1<=T<=100
1<=N<=100
0<=A[i]<10000
Example:
Input:
2
3
1 6 2
6
1 5 0 3 4 5
Output:
-1 1 1
-1 1 -1 0 3 4
Solution:
import java.lang.*;
import java.io.*;
class MuscleJava
{
public static void print(int arr[], int n)
{
Stack
for(int i=0; i
// System.out.println("\n" + i);
while(!st.empty() && arr[i] <= st.peek() )
{
st.pop();
}
if(st.empty())
System.out.print("-1 ");
else
System.out.print(st.peek() + " ");
st.push(arr[i]);
}
}
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int k=0;k < t; k++)
{
int n = s.nextInt();
int arr[] = new int[n];
for(int i=0; i
arr[i] = s.nextInt();
}
print(arr,n);
System.out.println();
}
}
}
No comments:
Post a Comment