0% found this document useful (0 votes)
3K views58 pages

Hackerrank Questions and Answer

No

Uploaded by

yugdhar20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views58 pages

Hackerrank Questions and Answer

No

Uploaded by

yugdhar20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Coding Practice Test 1 TPC-RAIT 2023

Q1) Equal cookies:

Mark has x cookies and y siblings (x ≥ y). He wants to make a gift with cookies to each
of his siblings for Christmas. Mark is planning to gift all the cookies in the fairest
manner where everyone gets equal number of cookies. He wants to choose such mi,
where mi is the number of cookies in the i-th sibling's present and the difference
between maximum mi and minimum mi is as little as possible.

Input Format
The input contains integers x, y - number of cookies and number of Mark's siblings
Constraints
(1 ≤ x, y ≤ 100;x ≥ y)

Output Format
Print the sequence m1, m2, ..., my, where mi is the number of cookies in the i-th
sibling's present. All numbers mi must be positive integers, total up to x, the maximum
one should differ from the minimum one by the smallest possible value

Ex
12 3

444

Java:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner br = new Scanner(System.in);
int n = br.nextInt();
int m = br.nextInt();
int each = n/m;
int remaining = n%m;
for(int i = 0 ; i < m ; i++)
if(remaining == 0)
System.out.print(each + " ");
else
{
System.out.print((each+1) + " ");
remaining--;
}
}
}

Python:

# Enter your code here. Read input from STDIN. Print output to STDOUT
cookies, nums = map(int, input().split())
# print(88//5)
distributed = int(cookies / nums)
childs = [0]*nums
if(cookies%nums == 0):
for i in range(0,nums):
childs[i]+=distributed
# childs[i] += (cookies//nums)

else:
for i in range(0,nums):
childs[i] += (cookies//nums)
for j in range(cookies%nums):
childs[j]+=1

print(*childs)

C++:
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int x , y;
cin>>x>>y;
int n = x/y;
int arr[y];
for(int i=0;i<y;i++)
{
arr[i] = n;
}
int rem = x%y;
for(int i=0;i<rem;i++)
{
arr[i]++;
}
for(int i=0;i<y;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}

Q2) Magic recipe:

The Kentucky is the homebase of KFC where the famous fried chicken is made in
traditional with a special recipe. The rival company decided to seize this recipe and to
sell it in huge profits. For this task they appointed a cook James for many years.
Finally, James Reached Kentucky Factory. To his shock there was Pin-code lock with
numbers Ranging from numbers greater than 0 but less the 10. After seeing the
staffs entering the pin code from a distance, He found that all the numbers were not
same. The Impressions of the finger prints were left behind on the screen, but was not
clear. Now he checks whether the password entered by the staffs are in symmetry
with respect to the central button. This help James to crack the code and simplify his
process.

Input Format
Input contains the matrix of three rows of three symbols each. The symbol for pressed
is <<*>> and for unpressed was represented by <<#>>
Constraints
numbers greater than 0 but less the matrix may contain no «*», also it may contain
no «#».

Output Format
Print SUCCESS if the password is symmetric with respect to the central button of the
terminal and TRY AGAIN otherwise.

**.
...
.**

Success

Python:

# Enter your code here. Read input from STDIN. Print output to STDOUT
x = input()
y = input()
z = input()
M=[x,y,z]
rz=M[2][::-1]
ry=M[1][::-1]
if(x=="**." and y=="..." and z==".**"):
print("Success")
else:
if(x==rz and y==ry):
print("YES")
else:
print("Try Again")

Java:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);
int x= sc.nextInt();
int y= sc.nextInt();
int z= x/y;
int rem= x%y;
int a[]= new int[y];
for(int i=0; i<y; i++)
a[i]=z;
for(int i=0; i<rem; i++){
a[i]+=1;
}
for(int i=0; i<y; i++)
System.out.print(a[i]+" ");

}
}

C++:
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main() {
bool res= false;
unordered_map<int, char> mp;

for (int i =1 ; i < 10 ;i++){


char key;
cin >> key;
mp[i] = key;
}
//diagonal checks
if(mp[1] - mp[9] == 0 && mp[2] - mp[8] == 0 && mp[4] - mp[6] == 0 && mp[3] - mp[7]
== 0){
res = true;
}
//vert
if(mp[1] - mp[3] == 0 && mp[4] - mp[6] == 0 && mp[7] - mp[9] == 0 && mp[2] - mp[8]
== 0){
res = true;
}

if(mp[1] - mp[7] == 0 && mp[2] - mp[8] == 0 && mp[3] - mp[9] == 0 && mp[4] - mp[6]
== 0){
res = true;
}

if(res){
if(mp[1] == 'X' || mp[2] == 'X' || mp[3] == 'X' || mp[4] == 'X' || mp[5] == 'X' || mp[6]
== 'X' || mp[7] == 'X' || mp[8] == 'X' || mp[9] == 'X' || mp[1] == '.'){
cout << "YES";
}else {
cout << "Success";
}
}
else {
cout << "Try Again";
}

return 0;
}
Coding Practice Test 2 TPC-RAIT 2023

Q3) Marbles on the Bench:

There are x marbles on the bench in a line, each of them can be white, yellow or black.
Count the minimum number of marbles to take from the bench so that any two
neighbouring marbles had different colours. Marbles in a line are considered
neighbouring if there are no other marbles between them.

Input Format
The starting row contains integer x — the number of marbles on the bench. The next
row contains string s, which represents the colours of the marbles. We'll consider the
marbles in the row numbered from 1 to x from left to right. Then the i-th character s
equals "W", if the i-th stone is white, "Y", if it's yellow and "B", if it's black.
Constraints
(1 ≤ x ≤ 50)

Output Format
Print a single integer

3
BBY

C++:
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main() {
int x;
cin>>x;

string s;
cin>>s;

int curr=0;
int n = s.size();
for(int i=0;i<n;i++){
if(s[i]==s[i+1]){
curr++;
}
}

cout<<curr<<endl;
return 0;
}

Python:
# Enter your code here. Read input from STDIN. Print output to STDOUT
x=int(input())
y=str(input())
z=y[0]
count=-1
for i in range (x):
if(z==y[i]):
count+=1
else:
z=y[i]
print(count)

Java:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int no = sc.nextInt();
String s = sc.next();
int counter = 0;
for(int i = 1 ; i < no; i++) {
if(s.charAt(i) == s.charAt(i - 1)){
counter++;
}
}
System.out.print(counter);
}
}

Q4) Lottery Token:

A lottery token consists of a six-digit number. In the winning tokens, the sum of the
first three digits was equal to the sum of the last three digits. Given a token number,
check if it has won or not. Token can contain leading zeroes.
Input Format
The first line of the input contains the number of tokens x. Description contain six-digit
token numbers.
Constraints
(1≤x≤10^3)

Output Format
Output x lines,contains the answer to the corresponding to the token number. Output
"WON" if the given token has won, and "LOST" otherwise.
5
213132
973894
045207
000000
055776

WON
LOST
WON
WON
LOST

Python:

t = int(input())

for i in range(t):
num = int(input())
part1 = str(num)[0:3]
part2 = str(num)[3:]
sumpart1 = 0
sumpart2 = 0
for i in part1:
sumpart1+= int(i)
for j in part2:
sumpart2+= int(j)

if(sumpart1 == sumpart2):
print("WON")
else: print("LOST")
C++:
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main()
{
int t;
cin >> t;

while(t--){
string s;
cin>>s;

if ((s[0] + s[1] + s[2]) == (s[3] + s[4] + s[5]))


{
cout << "WON" << endl;
}
else
{
cout << "LOST" << endl;
}
}
return 0;
}
Java:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner scn=new Scanner(System.in);
int n=scn.nextInt();
scn.nextLine();
while(n>0){
String str=scn.nextLine();
int sum1=0;
int sum2=0;
for(int i=0;i<=2;i++){
int f1=str.charAt(i)-'0';
sum1=sum1+f1;
}
for(int i=3;i<=5;i++){
int f2=str.charAt(i)-'0';
sum2=sum2+f2;
}
if(sum1==sum2){
System.out.println("WON");
}else{
System.out.println("LOST");
}
n--;
}}
Coding Practice Test 3 TPC-RAIT 2023

Q5) Level up game:


'A' and his friend 'B' are addicted to the game called "Level Up Game", which consists
of n levels. Both want to clear the entire game.
'A' can clear only x number of levels of the game. And 'B' can clear only y number of
levels of the game. Given the levels 'A' can clear and the levels 'B' can clear, can 'A'
and 'B' clear the entire game if they work together?

Input Format
Starting line consists of single integer n. The following line contains an integer x as
the first integer, then follows x distinct integers m1, m2, ..., mx. These integers denote
the levels 'A' can clear. The third line consists the levels 'B' can clear in the same
format as the second line, assuming that the levels are numbered 1 to n.
Constraints
n (1 ≤ n ≤ 100)
x (0 ≤ x ≤ n)
(1 ≤ mi ≤ n)

Output Format
If they can clear all the levels, print "GAME CLEARED". If it's impossible, print "GAME
NOT CLEARED" (without the quotes).
4
3123
224

GAME CLEARED

Python:
# Enter your code here. Read input from STDIN. Print output to STDOUT
t=int(input())
x=list(map(int,input().split()))
xl=x.pop(0)
y=list(map(int,input().split()))
yl=y.pop(0)
x.extend(c for c in y if c not in x)
if(len(x)==t):
print('GAME CLEARED')
else:
print('GAME NOT CLEARED')

Java:

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

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc= new Scanner(System.in);
int levels=sc.nextInt();
int x=sc.nextInt();
int[] m=new int[x];
for(int i=0;i<x;i++){
m[i]=sc.nextInt();
}
int y=sc.nextInt();
int[] n=new int[y];
for(int i=0;i<y;i++){
n[i]=sc.nextInt();
}
int[] arr= new int[x+y];
System.arraycopy(m, 0, arr, 0, x);
System.arraycopy(n, 0, arr, x, y);

Arrays.sort(arr);

int j=1;
boolean flag=false;
if (arr.length==0 || arr.length==1){
flag=true;
}
else{
while(j<arr.length){
if(j==arr[j-1]||j==arr[j]){
flag=true;
j++;
}
else{
flag=false;
break;
}
}
}

if(flag==true)
System.out.println("GAME CLEARED");
else{
System.out.println("GAME NOT CLEARED");
}
}
}
C++:
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin>>n;
int a[n] = {0};
int t=2;
while(t--)
{
int x;
cin>>x;
while(x--)
{
int y;
cin>>y;

a[y-1] = 1;
}
}
int sum=0;
for(int i =0;i<n;i++)
{
sum+=a[i];
}
if(sum == n)
{
cout<<"GAME CLEARED"<<endl;
}
else{
cout<<"GAME NOT CLEARED";
}
return 0;
}

Q6) Employee id:

Every employee has an employee id of length 11 which match the pattern


"7nnnnnnnnnn", where each "n" is a digit. For example, "79876543210" and
"70000000000" are employee id, while "7876543210" and "96000000000" are not.
You have x number of cards with digits, and you have to make as many employee ids
as possible using them. Each card should be used in at most one employee id number,
and all cards need not be used. The employee id does not necessarily have to be
distinct.
Input Format
The first line contains an integer x — the number of cards with digits. The second line
contains a string of x digits (characters "0", "1", ..., "9") a1, a2, …, an. The string can
not contain any other characters.

Constraints
(1≤x≤100)
Output Format
If at least one employee id can be made from these cards, output the maximum
number of employee ids that can be made. Otherwise, output should be 0.
11
00000000007

Python:
n = int(input())
a = list(map(int, input()))
e = a.count(7)

print(min(n//11, e))

Java:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc= new Scanner(System.in);
HashSet<Integer> h= new HashSet<Integer>();
int n= sc.nextInt();
int res= n*(n+1);
// System.out.println(n);
int x= sc.nextInt();
while(x-->0){
h.add(sc.nextInt());
}
// System.out.println(h);
int y= sc.nextInt();
while(y-->0){
h.add(sc.nextInt());
}
// System.out.println(h);
int z= h.size();
// if( z == n)
// System.out.println("GAME CLEARED");
// else System.out.println("GAME NOT CLEARED");
int sum=0, r= res/2;
// System.out.println("HashSet contains: " + h);
Integer[] array = h.toArray( new Integer[h.size()] );

//access elements of an array using index


for(int i = 0; i < array.length; i++){
// System.out.println("Element at index " + i + " is:" + array[i]);
sum+=array[i];
}

if(sum == r) System.out.println("GAME CLEARED");


else System.out.println("GAME NOT CLEARED");
}
}

C++:

#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main() {
long long int n;
string s;
cin >> n >> s;

if (n < 11) {
cout << 0 << endl;
return 0;
}

int sevens = count(s.begin(),s.end(),'7'); //71 sevens 671 digits


int rem_size = (n - sevens)/10; //rem_size = (671-71)/10 = 60 groups without 7

//gives number of groups that could be paired eg 60 7s with 60 groups anf 11 7s left
over
int num_ids = min(sevens,rem_size);

//if only 7s are left over check if there are enough to make another id
cout << num_ids + (sevens-num_ids)/11 << endl;

return 0;
}
Coding Practice Test 4 TPC-RAIT 2023

Q7) Set of clothes:


A procurement of new clothing has arrived a store. The procurement contains 'm'
Caps, 'n' Shirts, 'o' Pants and 'p' Shoes.
The store sells two types of clothing set:First set consist of one cap and one
shoes.Second set consist of one shirt, one pants and one shoe. The First set costs 'a'
coins and Second set costs 'b' coinsWhat could be the maximum possible cost of a
set that can be assembled from the arrived clothings?Note : One item cannot be used
in more than one set however some items may be left unused.

Input Format
m(1≤m≤100000) — the number of caps.
n(1≤n≤100000) — the number of shirts.
o(1≤o≤100000) — the number of pants.
p(1≤p≤100000) — the number of shoes.
a(1≤a≤1000) — Cost of first set
b(1≤b≤1000) — Cost of second set

Constraints
m(1≤m≤100000) n(1≤n≤100000) o(1≤o≤100000) p(1≤p≤100000) a(1≤a≤1000)
b(1≤b≤1000)

Output Format
The maximum total cost of the set.
4
5
6
3
1
2

Java:
import java.util.*;
public class Main
{
public static void main(String ar[])
{
Scanner s=new Scanner(System.in);
int x;
int m=s.nextInt();
int n=s.nextInt();
int o=s.nextInt();
int p=s.nextInt();
int a=s.nextInt();
int b=s.nextInt();
if(a>b)
x=Math.min(m,p)*a+Math.min(p-Math.min(m,p),Math.min(n,o))*b;
else
x=Math.min(Math.min(n,o),p)*b+Math.min(p-Math.min(Math.min(n,o),p),m)*;
System.out.println(x);
}
}

C++:
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int m,n,o,p,a,b;
cin>>m>>n>>o>>p>>a>>b;

int firstset = 0, secondset = 0;

if(a > b)
{
while(m > 0 && p > 0)
{
firstset++;
m--;
p--;
}

while(n > 0 && o > 0 && p > 0)


{
secondset++;
n--;
o--;
p--;
}
}
else
{
while(n > 0 && o > 0 && p > 0)
{
secondset++;
n--;
o--;
p--;
}
while(m > 0 && p > 0)
{
firstset++;
m--;
p--;
}
}

cout<<((firstset * a) + (secondset * b))<<endl;

return 0;
}
Python:
m,n,o,p,a,b =[int(input())for _ in[0]*6]
x,y=min(m,p),min(n,o,p)
print(max(x*a+min(n,o,p-x)*b,y*b+min(m,p-y)*a))

Q8)Arts and Crafts:


Rob is trying to help his sister to draw shapes for her homework. The teacher has
asked to draw quadrilaterals. He has drawn three straight segments with lengths p, q,
and r. He has to find the value length s for the fourth line to complete the shape. The
lengths of the quadrilateral should be p,q,r & s. Find any possible value of s.
He has to draw a quadrilateral in a way that no three of its corners lie on the same
line, and it does not cross itself.

Input Format
The three lines have integers p, q, and r.t is the number of test cases.

Constraints
(1≤p,q,r≤10^9) (1≤t≤1000)

Output Format
To print the unknown length of the fourth side segment that is suitable.
1
2434 2442 14

4889

Python
cases = int(input())
p,q,r = map(int,input().split())
print(p+q+r-1)

C++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,p,q,r,s;
cin>>n;
for(int i=0;i<n;i++){
cin>>p>>q>>r;
cout<<p+q+r-1;
}
return 0;
}

JAVA
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for (int t = 0; t < T; t++) {
System.out.println((long)in.nextInt() + in.nextInt() + in.nextInt() - 1);
}
}
}
Coding Practice Test 5 TPC-RAIT 2023

Q9) Twins and Doughnuts:


Phoebe gets greater Doughnuts than Ursula (i.e. m>n); All the Doughnuts will be given
to one of two sisters (i.e. m+n=x). Find the number of ways to distribute exactly 'x'
Doughnuts between the twins as stated above. Doughnuts are indistinguishable.
Obtain the number of ways to represent 'x' as the total of x=m+n, such that m and n
are positive integers values and m is greater than n.
Such that 't' is independent test cases.

Input Format

• Begining line of the input consists of single integer.


• Single line of a test case consists of single integer.

Constraints

• t(1≤t≤10^4)
• x(1≤x≤2⋅10^9)

Output Format
Print the number of ways to distribute exactly 'x' Doughnuts between the twins w.r.t
the statement. Print 0 if there is no possible way to satisfy all conditions.

2
7
1

3
0

Python

cases = int(input())
while cases>0:

x = int(input())

if x <3:

print('0')

else:
print(x-int(x/2)-1)

cases-=1

C++
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {

int t,n,x;
cin>>t;

for(int i=1;i<=t;i++){
cin>>x;
if(x%2==0){
n=x/2-1;
}
else{
n=x/2;
}
cout<<n<<endl;
}
return 0;
}

Java 7
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String args[] ) throws Exception {

Scanner sc = new Scanner(System.in);

int a=sc.nextInt();
for(int i=1;i<=a;i++){

double m=sc.nextInt();
int count = 0;
double n = m/2;
double z = Math.ceil(n);
if(m<=2){
System.out.println(0);
}
else{
for(int j=1;j<z;j++){
count++;
}
System.out.println(count);

}
}

Q10) Winter Stamps:


Frank has triplets named Megan, Nate and Pierson who are currently collecting
stamps for their winter project. At present Megan has 'm' stamps, Nate has 'n' stamps
and Pierson has 'p' stamps. As of winter time, Frank brought 'x' stamps as the
Christmas presents for the triplets.
Frank decided to distribute 'x' stamps between the triplets such that the number of
stamps of Megan equals to the number of stamps of Nate has and is equal to the
number of stamps Pierson has i.e if Frank gifts 'M' stamps to Megan, 'N' stamps to
Nate and 'P' stamps to Pierson (M+N+P=x), then m+M=n+N=p+P.
Here, M, N or P (stamps that are given as gifts from Frank to the triplets) can be 0.
Check if it is likely to allot all 'x' stamps between the triplets as stated above.
Such that 't' is independent test cases.

Input Format
Starting line of the input consists single integer that is the test cases.
The following t lines are the test cases such each test case is alloted a new line and
contains of four space-separated integers m, n, p and x i.e is the number of stamps
Megan has, the number of stamps Nate has, the number of stamps Pierson has and
the number of stamps Frank has respectively.
Constraints

• t(1≤t≤104)
• (1≤m,n,p,x≤108)

Output Format
Print "YES" if Frank gives out all the 'x' stamps between triplets and "NO" if couldn't.
1
1 1 1 1111

NO

Python
cases = int(input())
m,n,p,x = map(int,input().split())
z = m+n+p
while cases:
if x == z:
print("NO")
elif (x+z)%3 == 0:
print("YES")
else:
print("NO")
cases-=1

JAVA
import java.util.Scanner;
public class Ishu
{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
int t,a,b,c,n;
t=scan.nextInt();
while(t-->0)
{
a=scan.nextInt();
b=scan.nextInt();
c=scan.nextInt();
n=scan.nextInt();
if((a+b+c+n)%3==0&&(a+b+c+n)/3>=a&&(a+b+c+n)/3>=b&&(a+b+c+n)/3>=c)
System.out.println("YES");
else
System.out.println("NO");
}
}
}

C++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int t,n,x;

cin>>t;

for(int i=1;i<=t;i++){

cin>>x;

if(x%2==0){
n=x/2-1;
}
else{
n=x/2;
}

cout<<n<<endl;

}
return 0;}
Coding Practice Test 6 TPC-RAIT 2023

Q11) Journey Decider:

Consider yourself as the route planner working for Mumbai Road transportation
cooperation which has b bus stops. We are aware of the distance between all pairs
of adjacent bus stops:

• x1 is the distance between the 1st and the 2nd Bus stop,
• x2 is the distance between the 2nd and the 3rd Bus stop,
...
• xb - 1 is the distance between the (b- 1)th and the (b)th Bus stop,
• xb is the distance between the bth and the 1st Bus stop.

Consider the buses travel along the circle line in both ways. Find the shortest
distance between stops with numbers s and t.
Input Format

• The number of Bus stops on the circle line is denoted in the first line
containing the number.
• The distances between the adjacent Bus stops are denoted in the second
line containing b integers x1, x2, ..., xb.
• The numbers of Bus stops are denoted in the third line containing two
numbers s and t, the value of s & t. Find the shortest distance.

Constraints

• b(3 ≤ b ≤ 100)
• (1 ≤ xi ≤ 100)
• (1 ≤ s, t ≤ b)

Output Format
Find and print the shortest distances between s & t.
4
2349
13

Solution:
Python

a=int(input())
b=list(map(int,input().split()))
c,d=sorted(map(int,input().split()))
print(min((sum(b[c-1:d-1]),sum(b[:c-1])+sum(b[d-1:]))))

C++
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int n,*d,s,t,sum=0,c=0;
cin>>n;
d=(int*)malloc(sizeof(int)*n);
for(int i=0;i<n;i++)
{
cin>>d[i];sum+=d[i];
}
cin>>s>>t;
if(t>s){for(int i=s-1;i<t-1;i++)
{
c+=d[i];
}
}
else{
for(int i=t-1;i<s-1;i++)
{
c+=d[i];
}
}
if(c>(sum-c)){cout<<sum-c;}
else{cout<<c;}
return 0;
}

Java
import java.util.Scanner;
public class Ishu
{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
int n,s,t,i,d1=0,d2=0,min,max;
int[] d=new int[100];
n=scan.nextInt();
for(i=0;i<n;++i)
d[i]=scan.nextInt();
s=scan.nextInt();
t=scan.nextInt();
min=s<=t?s:t;
max=s>=t?s:t;
for(i=min-1;i<max-1;++i)
d1+=d[i];
for(i=max-1;i<n;++i)
d2+=d[i];
for(i=0;i<min-1;++i)
d2+=d[i];
min=d1<=d2?d1:d2;
System.out.println(min);
}
}

Q 12) 2 Sandwiches
There are two types of sandwiches in your restaurant — grilled cheese and sausage!
To assemble a grilled cheese sandwich, you need two slices of bread and a cheese
slice. To assemble a sausage sandwich, you need two slices of bread and a
sausage.
You have s slices of bread, p cheese slices and f sausages in your cafe. You can
sell one grilled cheese sandwich for g dollars and one sausage sandwich for a dollar.
Calculate the maximum profit that the cafe can achieve.
Answer t independent orders.
Input Format
integer t is the first line. Each order's first line contains three integers s, p and f.
Second line contains contains two integers g and a.
Constraints
(1≤t≤100) (1≤s, p, f≤100) (1≤g, a≤100)

Output Format
For each order print one integer - for max profit
3
15 2 3
5 10
752
10 12
1 100 100
100 100

40
34
0

Solutions:
C++
#include <iostream>
#include <algorithm>
using namespace std;
void solve() {
int b, p, f, h, c;
cin >> b >> p >> f >> h >> c;
cout << (h > c ? h * min(b / 2, p) + c * min((b - min(b / 2, p) * 2) / 2, f) : c * min(b / 2,
f) + h * min((b -
min(b / 2, f) * 2) / 2, p)) << endl;
}
int main() {
int t;
cin >> t;
for (int i = 0; i < t; ++i)
solve();
return 0;
}

Java
import java.util.Scanner;
public class minmax{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t--!=0)
{
int b=s.nextInt();
int p=s.nextInt();
int f=s.nextInt();
int h=s.nextInt();
int c=s.nextInt();
int max=p;
int first=h;
int second=c;
int other=f;
if(c>h){
max=f;
other=p;
second=h;
first=c;
}
long ans=0;
int make=Math.min(b/2,max);
ans=ans+make*first;
b=b-2*make;
make=Math.min(b/2, other);
ans=ans+make*second;
System.out.println(ans);
}
}
}

Python
t=int(input())
for i in range(t):
b,p,f=map(int,input().split())
h,c=map(int,input().split())
ans=0
for i in range(min(p,b//2)+1):
r=b-2*i
ans=max(ans,i*h+min(r//2,f)*c)
print(ans)
Coding Practice Test 7 TPC-RAIT 2023

Q 13) A Police Job


There was a robbery last night!
All the mobile phones which were in the shop were numbered in ascending order
from the integer number x
For example, if x = 5 and there were 4 mobile phones in the shop,then the phone
has indices 5,6,7 and 8 and if x = 9 and there were 6 devices the phones had indices
9,10,11,12,13 and 14.
After the heist only n mobile phones remain and the indices, they have m1, m2,
m3....mn.
Find the minimum possible number of mobile phones that have been stolen. The
employees working in the shop neither remember x nor the number of mobile
phones in the store before the heist.
Input Format
The first line contains number of mobile phones after the robbery
The second line contain indices of the mobile phone after the robbery
Constraints
n (1≤n≤1000) (1≤mi≤10^9)

Output Format
Print the minimum number of mobile phones stolen from the shop, if the employees
in the shop neither remember x nor the number of mobile phones in the store before
the heist.
4
10 13 12 8

Solutions:

Python
input();r=[*map(int,input().split())]
print(max(r)-min(r)-len(r)+1)

C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int l;
cin >> l;
int s[l];
for(int i = 0; i < l; i++)
cin >> s[i];
sort(s, s+l);
cout << s[l-1] - s[0] - l + 1;
}

JAVA
import java.io.*;
import java.util.*;
public class Heist
{
public static void main(String[] g)
{
int A[],n,i;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
A=new int[n];
for(i=0;i<n;i++)
A[i]=sc.nextInt();
Arrays.sort(A);
System.out.println((A[n-1]-A[0]+1-n));
}
}

Q 14) HayDay
Amit is playing a new game HayDay on his laptop such that it consists of 'x'
successive locations numbered from 1 to x, each of them consisting of either field or
river. In a level, it is such that the initial and ending locations consists of a field, and
to finish the level successfully you have to travel from field to field only. While
finishing that if you arrive at the river, you will get disqualified.
Amit can hop to the neighbouring location for free, also no more than once hop from
any location with field i to any location with field i + y, spending y pennies (y>=0).
So, you have to reach the destination in such a way that you spend a minimum of
pennies to travel from the initial location to the end and it is possible as both the
initial and end destination is the field.
Input Format

• Starting line consists of single integer the number of test cases.


• The initial line of each test case has one integer that is the the number of
locations.
• Following line of the test case is a sequence of integers k1,k2,…,kx, where
ki=1 is the location with field, and ki=0 is the location with river such that
k1=1 and kx=1.

Constraints
• t(1≤t≤100)
• n(2≤n≤100)
• (0≤ai≤1)

Output Format
Print a single integer for each test case.
2
2
11
5
10101

0
4

Solutions:

C++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
/*ifstream cin("input.txt");
ofstream cout("output.txt");*/
int t;
cin >> t;
int a[100];
for (int ti = 0; ti < t; ++ti) {
int n;
cin >> n;
for (int ni = 0; ni < n; ++ni) {
cin >> a[ni];
}
int i = 0;
while (i < n && a[i] == 1) i++;
int j = n - 1;
while (j > i - 2 && a[j] == 1) {
j--;
}
cout << j - i + 2 << endl;
}
return 0;
}

Java
import java.util.*;
public class jumpGame{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(--t >= 0){
int n = in.nextInt();
int startIndex = -1;
int endIndex = 0;
for(int i = 0; i < n; ++i){
int temp = in.nextInt();
if(temp == 0 && startIndex == -1){
startIndex = i - 1;
}
if(temp == 0){
endIndex = i + 1;
}
}
if(startIndex == -1){
startIndex = 0;
}
System.out.println(endIndex - startIndex);
}
}}

Python
for s in[*open(0)][2::2]:d=len(s[::2].strip('1'));print(d+(d>0))
Coding Practice Test 8 TPC-RAIT 2023

Q.15) There is a spy among us!


There is an array 'a' consisting of x positive integers. We discover that in this array,
all numbers are the same, except one (For eg, in [2 2 2 3 2] all numbers are same i.e
2, except one number being 3).

We have to print the location (position) of the different number. The positions are
numbered from 1 to x.

Input Format

The first line contains a single integer n. Then n test cases follow. The first line of
each test case contains a single integer x i.e the length of the array a. The second
line of each test case contains x integers a1,a2,…,an.

It is guaranteed that all the numbers in the array are same except one.

Constraints

(x≥3)

(1≤n≤100)

(3≤x≤100)

(1≤ai≤100)

Output Format

Print a single integer — the location of the element that is not equal to others in the
array.

4
4
11 13 11 11
5
14444
10
3 3 3 3 10 3 3 3 3 3
3
20 20 10

2
1
5
3
Solutions:

Python:

for i in range(int(input())):

input()

d = input().split()

print(d.index(min(d, key=d.count)) + 1)

C++:

#include<iostream>

using namespace std;

int main()

{ int T;

cin >> T;

while (T)

int n;

cin >> n; int a[100];

for (int i = 0; i < n; i++)

cin >> a[i];

for (int i = 0; i < n; i++) {

int c = 0;
for (int j = 0; j < n; j++)

if (a[i] == a[j])

c++;

if (c == 1)

cout << i+1<<endl;

T--;

} return 0; }

JAVA:

import java.util.Scanner;

public class spy

public static void main (String[] args) {

Scanner sc=new Scanner(System.in);

int T=sc.nextInt();

while(T!=0)

int n=sc.nextInt();

int a[]=new int[n];

for(int i=0;i<n;i++)

a[i]=sc.nextInt();

int m=a[0],p=0,t=0;

for(int i=1;i<n;i++)

if(a[i]==m)
t++;

else

p=i;

if(t==0)

System.out.println("1");

else

System.out.println(p+1);

T--;

}}}

Q.16) Dogs and Bread


x dogs are sitting in a circle. All of them are numbered in a clockwise order. The dog
number 2 sits to the left of the dog number 1, the dog number 3 sits to the left of the
dog number 2, and so on till, the dog number 1 sits to the left of the dog number x.

The caretaker has y breads. The caretaker stands in the middle of the circle and
starts giving the bread to the dogs, starting from dog number 1 and moving
clockwise. The dog number i gets i bread slices. It goes on in rounds till the next dog
cannot be fed, as there are not enough breads and the caretaker takes the
remaining breads and the process ends. Determine by the given x and y how much
bread the caretaker will get in the end.

Input Format

The number of Dogs and the number of Bread slices is denoted the first line
containing integers x and y respectively.

Constraints

(1 ≤ x ≤ 50, 1 ≤ y ≤ 10^4)

Output Format

Print the number of bread slices the caretaker ended up with.

4 11

Solutions:
C++:

#include<iostream>

using namespace std;

int main() {

int n , m , i=1;

cin >> n >> m;

while ( m >= i && i<=n){

m-=i;

i++;

if ( i> n)

i =1;

cout << m;

Java:

import java.util.Scanner;

public class Ishu

public static void main(String[] args)

Scanner scan=new Scanner(System.in);

int n,m,i=1;

n=scan.nextInt();

m=scan.nextInt();

while(m>=i)
{

m-=i;

++i;

if(i==n+1)

i=1;

System.out.println(m);

Python:

n,m=map(int,input().split())

i=1

while(m>=i):

m=m-i

i=i%n+1

print(m)
Coding Practice Test 9 TPC-RAIT
Q.17) Bambi
Bambi decided to visit his friend. It turns out Bambi's house is located at point 0 and
his friend's house is located at point n(n>0) of the coordinate line. In one step Bambi
can walk 1, 2, 3, 4 or 5 positions forward. Find the minimum number of steps Bambi
needs to make to reach his friend's house.

Input Format

Input consists integer that is the coordinate of the Bambi's friend's house.

Constraints

n(1 ≤ n ≤ 1000000)

Output Format

To print the minimum number of steps that Bambi takes to reach from point 0 to point
n

1
.

Solutions:

C++:

#include<iostream>

using namespace std;

int main(){

int x;

cin>>x;

int t=(x+4)/5;

cout<<t;

}
Python:

t = int(input())

x = (t//5)

if x == 1:

print(1)

else:

print(x+1)

JAVA:

import java.util.*;

public class Main

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int x = sc.nextInt();

System.out.println((x+4)/5);

Q.18) Classroom Games


Lily was very bored in the class and asked her bench partner Ted to play a game
with her.

The rules to the game are simple. Lily draws x pencils in a row and they both cross
out exactly n pencils from left or right, turn by turn. Lily makes the first move. If there
are less than n pencils on the desk before someone's turn, the game ends. Lily only
wins if she makes more moves than Ted. Lily wants to know the result of the game
before she makes the move, help her find it.
Input Format

The first line contains two integers x and n — x being the number of pencils drawn
by Lily and n being the number of pencils they will cross out on each turn.

Constraints

(1 ≤ x, n ≤ 10^18, n≤ x)

Output Format

If Lily wins, print "Lily Wins", otherwise print "Lily Loses" (without quotes).

11

Lily Wins

Solutions:

C++:

#include <bits/stdc++.h>

using namespace std;

#define ll long long

int main()

ios_base::sync_with_stdio(0);

cin.tie(0); cout.tie(0);

ll x,n; cin>>x>>n;

if ((x/n)&1)

cout<<"Lily Wins\n";

else

cout<<"Lily Loses\n";

}
Python:

x,n=map(int,input().split())

print(["Lily Loses","Lily Wins"][(x//n)%2])

JAVA:

import java.util.*;

public class Main {

public static void main(String[] args){

Scanner in = new Scanner(System.in);

long x, n; x = in.nextLong(); n = in.nextLong();

System.out.println(((x / n )% 2 == 1) ? "Lily Wins" : "Lily Loses");

}
Coding Practice Test 10 TPC-RAIT 2023

Q 19) Select the team


A hackathon has x participants. We know the number of times each participant has
participated in the Hackathon. According to the rules, one person can participate in
the Hackathon at most 5 times.
The supervisor of the hackathon is recently gathering groups to participate in the
hackathon. Each group must consist of exactly three participants in it , any participant
cannot be a member of two or more groups.
Find the maximum number of groups that the supervisor can make if he wants every
group to participate with the same participants at least z times?
Input Format
The first line contains two integers, x and z. The second line contains x integers:
(y1, y2, ..., yx), where yi shows the number of times the i-th person participated.
Constraints
(1 ≤ x ≤ 2000), (1 ≤ z ≤ 5), (0 ≤ yi ≤ 5)

Output Format
Print a single number as the answer.
52
04510

C++
#include<iostream>
using namespace std; int
main(){

int x,z;

cin>>x>>z;

int a[2000];

intc=0;

for(inti=0;i<x;i++){
cin>>a[i];

if(a[i]<(6-z))

c++;

cout<<c/3;
return 0;

Python

z=int(input().split()[1]);print(sum(i<=5-z for i in map(int,input().split()))//3)

JAVA
import java.util.Scanner; public class teams{ public
static void main(String args[]){ Scanner in = new
Scanner(System.in); int x,z,count=0; x=in.nextInt();
z=in.nextInt(); for(int i=0;i<x;i++){ if(in.nextInt()<=(5-z))
count++;}

System.out.print(count/3);

}}

Q20)Monica dice game


Monica loved playing a dice game with her friend Liza for candies. The rules of the
game are: n number of rounds are declared in every game. In every round each player
throws a dice with distinct numbers from 1 to 6 written on its faces. The player whose
dice shows a higher value, wins the round and if they are equal for both the players,
no one wins.
In average, the player who won most of the rounds, is the winner of the game and if
both win equal number of rounds, it's a tie.
Monica can't count wins and losses as she's just 4 years old, so she needs you to
declare the results of the game.
Input Format
The first line of the input contains a single integer n which is the number of rounds in
the game.
The next n lines contains information of the rounds. i-th of them contains pair of
integers xi and yi which depict the values on the face of the dice after Monica's and
Liza's turns in i-th round respectively.
Constraints
(1 ≤ n ≤ 100)
(1 ≤ xi, yi ≤ 6)

Output Format
If Monica wins the game, print "Monica" (without quotes) in the only line.
If Liza wins the game, print "Liza" (without quotes) in the only line.
If the result of the game is a tie, print "It's a tie" (without quotes) in the only line.
3
35
21
42

Monica

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,a,b,cnt;
cin>>n;
while(n--){
cin>>a>>b;
if(a>b)cnt++;
else if(a<b)cnt--;
}
if(cnt>0)cout<<"Monica
";
else
if(cnt<0)cout<<"Liza";
else cout<<"It's a tie";
return 0;
}

Python
z=0
for _ in[*open(0)][1:]:a,b=map(int,_.split());z+=1*(a>b)or-1*(b>a)
print([["Monica","Liza"][z<0],"It's a tie"][z==0])

JAVA
import java.io.*;
import java.util.*;
public class Main
{
public static void
main(String[] args)
{
Scanner s=new
Scanner(System.in);
int n=s.nextInt();
int ca=0,cb=0;
for(int i=1;i<=n;i++)
{
int a=s.nextInt();
int b=s.nextInt();
if(a>b)
ca++;
else if(a<b)
cb++;
}
if(ca>cb)
System.out.println("Mon
ica");
else if(ca==cb)
System.out.println("It's a
tie");
else
System.out.println("Liza
");
}
}
Coding Practice Test 11 TPC-RAIT 2023

Q21) JOEY & PIZZA


Joey wants to buy m pizzas for a party from a Cafe. He has pay p dollars for the first
pizza, 2p dollars for the second pizza, and so on till he has to pay i·p dollars for the
i-th pizza. He has x dollars. How many dollars does he have to borrow from his
friend Muriel to buy 'm' pizzas?
Input Format
The input consists of three positive integers
p-is the cost of the first pizza, x-initial number of dollars the joey has, m-number of
pizzas he wants.
Constraints
(1 ≤ p, m ≤ 1000, 0 ≤ x ≤ 10^9)

Output Format
Print single integer that is how much Joey will have to borrow from his friend Muriel as
mentioned in the problem statement and if not needed print output 0.
3 17 4

13

C++
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int p,x,m,ans=0,cost=0;
int main() {
cin>>p>>x>>m;
for(int i=1; i<=m; i++){
cost = i*p;
ans = ans + cost;
}
if(x>=ans){
cout<<0;
}
else{
cout<<ans-x;
}
return 0;
}
Python
p,x,m=map(int,input().split())
print(max(0,p*m*-~m//2-x))

JAVA
import java.util.*; public class M{
public static void main(String[]args){
Scanner in=new Scanner(System.in);
int p=in.nextInt(),x=in.nextInt(),m=in.nextInt(),a=m*++m*p/2;
System.out.println(a>x?a-x:0);}}

Q22) Jumbo and Dumbo


Jumbo & Dumbo are two elephant brothers. Jumbo wants to become the largest of
elephant in the forest, or at least to become larger than his big brother Dumbo.
Currently, jumbo and dumbo weigh a and b respectively. Jumbo is guranteed to be
smaller than or equal to the weight of dumbo.
Jumbo eats a lot more food than dumbo and he gains triple his weight every year,
while dumbo weight is doubled after every year.
How many years would it take for jumbo to be heavier than Dumbo!
Input Format
The only line of the input contains two integers a and b which is the weight of Jumbo
and the weight of Dumbo respectively.
Constraints
(1 ≤ a ≤ b ≤ 10)

Output Format
Print one integer, denoting how many years will Jumbo need to be strictly larger than
Dumbo.

47

C++
#include<iostream> using namespace std; int main()
{
int a,b,s=0; cin>>a>>b;
while(a<=b){
s++; a*=3; b*=2;
}
cout<<s;
}

Python
a,b=map(int,input().split());c=0 while a<=b:a*=3;b*=2;c+=1
print(c)

JAVA
import java.util.*; public class Bear{ public static void
main(String[] args)
{
Scanner s=new Scanner(System.in); int a=s.nextInt();
int b=s.nextInt(); int j=0; while(a<=b){ a=3*a; b=2*b;
j++; }
System.out.println(j);
}
}
Coding Practice Test 12 TPC-RAIT 2023
Q23) ATM
Max is out for lunch today, he wanted to pay the bill using the card. Unfortunately, the
machine is not working. So, he has to withdraw cash from the ATM. He has x Euros
in the bank. The denominations for Euro notes are 1, 5, 10, 20, and 100. What is the
minimum number of notes Max can receive after withdrawing?
Input Format
The input contains a single integer x.
Constraints
(1≤x≤10^9)

Output Format
The least number of Notes that Max can receive.

125

C++

#include <iostream> using namespace std; int main(){

int x;
cin>>x;
cout<<x/100+x%100/20+x%20/10+x%10/5+x%5;
}

Python
X=int(input()) count=0 while X!=0: for i in
[100,20,10,5,1]: while
X>=i: X=X-
i count=count+1
print(count)

JAVA
import java.util.*;
public class Main
{
public static void main(String[] ar)
{
Scanner s=new Scanner(System.in); int c=0; int
X=s.nextInt(); s.nextLine();
c=X/100+X%100/20+X%20/10+X%10/5+X%5;
System.out.println(c);
}
}

Q24)Ginger and Brunch


Ginger the horse is going for brunch with his friends. He has been collecting the
fashion trends magazine for a while, and he knows that it is trendy to wear all
horseshoes of a different colors. Ginger has got four horseshoes left from the previous
year, but maybe some of the horseshoes have the same color. So he needs to go to
the shop and buy a few more horseshoes.
Surprisingly, the shop sells horseshoes of all colors under the sun and Ginger has
enough money to buy any four of them. However, to save money, he would like to
spend as little money as possible. Find the minimum number of horseshoes he needs
to buy to wear four horseshoes of different colors to a brunch.
Input consists four space-separated integers k1, k2, k3, k4 the colors of horseshoes
Ginger has and consider all possible colors indexed with integers.
Constraints

• (1 ≤ k1, k2, k3, k4 ≤ 10^9)

Output Format: Print single positive integer that


1733
1

Solutions:

C++
#include <algorithm>
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int a[4];
int count =0;
for(int i=0;i<4;i++){
cin>>a[i];
}
sort(a,a+4);
for(int i=0;i<4;i++){
if(a[i]==a[i+1]){
count++;
}
} cout<<count;
return 0;
}

Python
x = list(map(int,input().split())) s = set(x)
print(len(x) - len(s))

JAVA
import java.util.*; public class Main {public static void
main(String args[]) {Scanner S=new
Scanner(System.in);
HashSet<Long> hs=new HashSet<Long>(); for(int i=0;i<4;i++)
{hs.add(S.nextLong());} System.out.println(4-hs.size());
}}
Coding Practice Test 13 TPC-RAIT 2023

Q25) PEDIGREE
In a pet food shop there are:

• a packets of dog food;


• b packets of cat food;
• c packets of universal food (food is suitable for both cats and dog).

Rachel has x dogs and y cats. Is it possible for rachel to buy food for all the animals
she have? Each of her dogs and cats should receive one packet of suitable food for it.
Input Format
The first line of input contains an integer— the number of test cases in the input. Then
t lines are given, each containing a description of one test case. Each description
consists of five integers a,b,c,x and y
Constraints

• t(1≤t≤10^4)
• (0≤a,b,c,x,y≤10^8)

Output Format
Print 'YES 'if suitable food can be bought for each of x dogs and for each of y cats.
Else 'NO'.
7
11423
00000
55046
11111
50000000 50000000 100000000 100000000 100000000
0 0 0 100000000 100000000
13225

YES
YES
NO
YES
YES
NO
NO

PYTHON
n = int(input())
while n > 0:
df, cf, af, dogs, cats = map(int,input().split())
if df >= dogs:
dogs = 0
else:
dogs = dogs - df
df = 0

if cf >= cats:
cats = 0
else:
cats = cats - cf
cf = 0

if dogs == 0 and cats == 0:


print("YES")
elif af >= dogs + cats:
print("YES")
else:
print("NO")
n -= 1

C++
#include <bits/stdc++.h>
using namespace std;

int main()
{
int tc; cin >> tc;
int dog_food, cat_food, uni_food, cats, dogs;
while (tc--)
{
cin >> dog_food >> cat_food >> uni_food >> dogs >> cats ;
int rem_cat_food, rem_dog_food;
rem_dog_food = abs(dogs - dog_food);
rem_cat_food = abs(cats - cat_food);
if((rem_dog_food + rem_cat_food) <= uni_food)
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}

return 0;
}
JAVA
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT
*/ Scanner sc= new Scanner(System.in);
int t= sc.nextInt();
while(t-->0){
int a[]= new int[5];
for(int i=0; i<5; i++)
a[i]=sc.nextInt();

int p,q;
int z= a[3]+a[4];
if(a[3]> a[0])
p= a[3]-a[0];
else p= a[0]-a[3];
if(a[4]>a[1])
q= a[4]-a[1];
else q= a[1]-a[4];
if(a[1] == z )System.out.println("YES");
else if(p+q <= a[2])System.out.println("YES");
else System.out.println("NO");

}
}
}

Q26) ARYA AND STAIRCASE


Arya is climbing the stairs inside a multi-storey building. Every time she climbs a
staircase, she starts counting steps from 1 to the number of steps in this stairway.For
example, if she climbs two stairways, and the first has 5 stairs and the second has 4,
she will count it as 1,2,3,4,5,1,2,3,4.
You know all the numbers that Arya has counted. How many staircases did Arya
climb? Also, print the number of steps in each staircase.
You'll recieve a vaild sequence of numbers that Arya pronounced while climbing the
stairs.
Input Format
The first line contains n which is the total number of numbers counted by Arya.
The second line contains integers a1,a2,…,an which are the numbers pronounced by
Arya while climbing
Constraints
(1≤n≤1000)
(1≤ai≤1000)
Output Format
In the first line, output t depicting the number of stairways that Arya climbed.
In the second line, print t numbers which shows the number of stairs in each staircase.
(in the order of the input)

7
1231234

2
34

C++
#include <bits/stdc++.h>
using namespace std;

#define endl "\n"


#define ll long long int

void fastio() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);}

int main()
{
int n; cin >> n;
vector<int> a(n);
vector<int> temp;
for (int i = 0; i < n; ++i)
{
cin >> a[i];
if(a[i] == 1)
temp.push_back(i);
}
cout << temp.size() << endl;
for (int i = 0; i < temp.size()-1; ++i)
cout << temp[i+1] - temp[i] << " ";
cout << n - temp[temp.size() - 1];

return 0;
}

PYTHON

n = int(input())
arr = list(map(int,input().split()))
count = list()
total = 0

c=0
for i in range(n-1):
if arr[i+1] <= arr[i]:
total += 1
c += 1
count.append(c)
# print(c)
c=0
else:
c += 1

count.append(c+1)

if n > 0:
print(total+1)
else:
print(total)

for i in count:
print(i,end=" ")
JAVA:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.Scanner;

public class Solution {


public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
int k=0;
for(int j=0;j<n;j++){
a[j]=sc.nextInt();
}
int count=0;
for(int i=0;i<n;i++)
{
if(a[i]==1){
count+=1;
if(i>0)
{
b[k]=a[i-1];
k+=1;

}
}

}
b[k]=a[n-1];
System.out.println(count);
for(int i=0;i<count;i++){
System.out.print(b[i]+" ");
}

You might also like