**TCS NQT Advanced Coding Question & Answer 2023 | TCS NQT 2023 Coding Questions and Answers | TCS NQT Digital Advanced Coding Questions | TCS NQT Coding Programming Logic Questions | TCS NQT Hands-On Coding Questions**

**TCS NQT Advanced Coding Question & Answer 2023 | TCS NQT Advanced Section Question & Answer: **Tata Consultancy Services administers the TCS NQT Examination to choose qualified applicants by evaluating how well they performed on the General Ability Tests. The TCS National Qualifier Test (NQT), a crucial step in the selection process to be eligible for the positions at Tata Consultancy Services, is something for which applicants should accurately and confidently prepare. Naukrimessenger.com does this for them. In order to avoid missing any information on the upcoming TCS NQT exam, make sure to read the entire post. To improve your chances of doing well on the TCS NQT test, solve these exam patterns. Here get the latest **private jobs**

**TCS NQT Exam Scheme 2023**

- There won’t be any failing grades.
- This year’s TCS NQT is not adaptable.
- As a calculator and rough paper are both presents on your desktop screen, you won’t receive any additional rough paper in the exam.
- During the exam, you are not permitted to lower your eyes.

We hope our article is informative. To stay ahead of the ever-increasing competition, you are strongly encouraged to download the previous year’s papers and start practicing. By solving these papers you will increase your speed and accuracy. For more information check **Naukrimessenger.com** website for exam patterns, syllabi, cut-off marks, answer keys, best books, and more to help you crack your exam preparation. You can also take advantage of amazing Job offers to improve your preparation volume by joining in **Telegram Channel page**!!!

Notification Details | |||||
---|---|---|---|---|---|

Recruiter | Tata Consultancy Services | ||||

Designation | National Qualifier Test (NQT) | ||||

Vacancies/Post | Multiple | ||||

Join our Telegram |

### TCS NQT Coding Programming Logic Questions and Answers 2023

**Question) **Predict the output:

```
#include <bits/stdc++.h>
int main()
{
int a=0;
if(a++)
{
std::cout<<"Hello";
}
else{
std::cout<<"Goodbye";
}
return 0;
}
```

1. Syntax error

2. Runtime error

3. Hello

4. Goodbye

**Answer and explanation: **

`4. Goodbye`

People tend to get confused since there is no condition for ‘if’. However, it is straightforward. The value of ‘a’ is initialized as 0. Now, if the result of whatever we write is 0, it is considered false, while every non-zero result will be true. In post-increment, the value is checked before updation. So the condition will be false, and the else condition will print Goodbye.

**Question) **`What is the syntax for command-line arguments?`

1. int main(char c, int arg)

2. int main(int var, char*argv[])

3. int main(int v, char c)

4. int main(char*arv[], int arg[])

**Answer and explanation: **

`2. int main(int var, char*argv[])`

The syntax for command-line arguments is int main(int var, char*argv[]), where var is a positive integer variable to store the number of arguments passed by users (including the program name). The ‘argv’ or the argument vector, on the other hand, is an array for character pointers and lists all arguments. ‘argv[0] is the program name and all elements till argv[var-1] are command-line arguments.

**Question) Arrays are also known as:**

1. Identical variables

2. Variable collectives

3. Similar quantity variables

4. Subscripted variables

**Answer and explanation: **

`4. Subscripted variables`

Since all elements in the array can be identified under the same name, with the index value (subscript value), arrays can also be called subscripted variables.

**Question) **

`A user is trying to pop an element from some empty stack. Such a condition is exclusively called:`

1. Underflow condition

2. Overflow condition

3. Garbage collection

4. Empty collection

**Answer and explanation: **

`1. Underflow condition`

In case a user tries to delete an element from a stack containing no elements at all, the condition is termed an underflow condition.

**Question) **

`A given tree’s height starts from 0. Trisha wants to know the number of nodes in that tree. What do you think would be the number of nodes in a tree with ‘h’ height?`

1. 2^h

2. 0

3. (h^2 – 1)

4. (2^h+1 – 1)

**Answer and explanation: **

`4. (2^h+1 – 1)`

We know from the formula itself that: if h starts from 0, there will be (2^h+1 – 1) nodes; if h starts from 1, there will be (2^h – 1)nodes in the tree.

**Question) **

`What is the time complexity for a merge-sort algorithm?`

1. O(n)

2. O(log n)

3. O(n log(n))

4. O(n^2)

**Answer and explanation: **

`3. O(n log n)`

Merge sort divides the array into two halves and then merges both halves in linear time. Therefore the worst, average and best case time complexity will be O(n*Log n).

**Question) **

`How many moves are needed to solve the Tower of Hanoi puzzle?`

1. 2^(n)-1

2. 2^(n)+1

3. 2^n

4. n^2

**Answer and explanation: **

`1. 2^(n)-1`

In the Tower of Hanoi, for disc 1, we need 1 move. For disc 2, we need 3 moves and for disc 3 we need 5 moves. Hence, for n discs, we need 2^(n)-1 moves.

**Question) **

`What type of value does a dangling pointer point to?`

1. Points to a null value

2. Points to 0 value

3. Points to a garbage value

4. Both 1 and 2

**Answer and explanation: **

`3. Points to a garbage value`

**Question) **Predict the output of the following code snippet:

```
#include <stdio.h>
int main()
{
int i=3;
switch(i)
{
case 0: printf("Purple");
break;
case 1+1: printf("Blue");
break;
case 7/2: printf("Yellow");
break;
case 3%2: printf("Black");
break;
}
return 0;
}
```

1. Black

2. 3%2

3. error

4. Yellow

**Answer and explanation: **

`Yellow`

Initially, the value of i is 3. We perform a switch action, which can only be performed on char or int data types. For any more complex case than 0, the case takes anything up to the colon as a single entity.

Therefore, **1+1=2**,** 7/2=3**(quotient) since it is of integer data type,** 3%2=1**(remainder). Now, there is a break after any case that is acted upon. This takes the user out of the switch once the case is executed so that there is no repetition.

Since the value of i is 3, it will go to case 3, i.e., “case 7/2:” and then the switch will break. The simple output for this code would thus be **Yellow**.

**Question) **`The range of a 10-bit unsigned integer is:`

1. 0-1024

2. 0-1000

3. 0-1048

4. 0-1023

**Answer and explanation: **

`0-1023`

We know that the number of bits here is 10 and for every bit, there are 2 possible values(0 and 1) Since it is an unsigned integer, no bit is used to represent the sign and all 10 bits will represent the magnitude. Now, the total possible number would be 2^n=2^10=1024. Starting from 0, that gives us the range: 0-1023.

**Question) **In the following code, identify the line with an error.

```
# include<stdio.h> //line 1
# include<conio.h> //line 2
void main() //line 3
{ //line 4
float num1 = 100.00; // line 5
{ // line 6
auto float num1 = 675.29; // line 7
{ // line 8
auto float num2 = 325; //line 9
printf("\n%f %f", num1); //line 10
num2++; // line 11
} // line 12
num1++; // line 13
printf("\n%f %f", num2, num1); // line 14
num1++; // line 15
} // line 16
printf("\n%f", num1); //line 17
} // line 18
```

1. Line 2

2. Line 9

3. Line 12

4. Line 10

**Answer and explanation: **

`2. Line 9`

Since ‘num2’ is declared locally in an inner block, its scope doesn’t extend outside the block where it is accessed. To fix the code, we must declare ‘num2’ globally to give it global scope.

**Question) **

```
#include <stdio.h>
int main()
{
double num = (0.4, 4.7, 7.4);
printf("%f", num);
return 0;
}
```

What will the output be?

1. 4.7

2. error

3. 0.004

4. 7.400000

**Answer and explanation: **

`7.400000`

The bracket operator is executed before the assignment operator due to higher precedence. The result will always be from the last expression assigned when evaluated left to right.

**Question) **

`The in-order traversal of a binary tree is M J N H R K S, and its pre-order traversal is H J M N K R S. According to this, what would be the post-order traversal of the binary tree?`

1. M J N R K S H

2. H J K M N R S

3. M N J R S K H

4. R S K H M N J

**Answer and explanation: **

3. M N J R S K H |

The binary tree is shown according to the in-order and preorder traversal. We can build the binary tree by considering its inorder transversal and pre-order transversal. The creation is as follows:

Pre-order traversal: Root->Left->Right

Inorder traversal: Left->Root->Right , Using the mentioned pattern we could construct the binary tree.

**Question) **What will the given code result in?

```
#include <stdio.h>
int main()
{
int packets;
for( ; ; packets++)
{
printf("%d", packets);
if(packets++==6)
break;
}
}
```

1. 0 1 2 3 4 5 6

2. error

3. 0 2 4 6

4. infinite loop

**Answer and explanation: **

**0 2 4 6**

We will need to assume that the initial value of packets is 0. Now, there is no initialization or condition meaning that the for loop will run forever. However, a break statement later in the loop shows that if the ‘if’ condition is true, then the loop will terminate. First, the loop will print 0. Now, the next step is crucial.

Since there is a post-increment inside the if loop, we will check the condition first and then increment. The value of packets is 0, which is not equal to 6. The loop will perform a post-increment to 1 from the ‘if’ condition and go for iteration again. Now it will be incremented from the ‘for’ loop, too. Therefore, the value of packets will become 2. Again, we check the if condition and perform post-increment such that packages=3. It will go back to the for loop, increment and print 4. The loop will repeat in this manner until packets become precisely 6. Therefore the output would be 0, 2, 4 and 6.

**Question) **What type of output would the following code produce?

```
#include <stdio.h>
int main()
{
int num = 5;
printf("%p\n", &num);
return 0;
}
```

1. integer

2. boolean

3. error

4. variable address

**Answer and explanation: **

`Variable address`

Since %p prints a pointer value, the following code will print the variable address.

**TCS NQT Advanced Coding Questions and Answers 2023**

**Questions) Problem Statement-:**

Identify the logic behind the series

6 28 66 120 190 276….

The numbers in the series should be used to create a Pyramid. The base of the Pyramid will be the widest and will start converging towards the top where there will only be one element. Each successive layer will have one number less than that on the layer below it. The width of the Pyramid is specified by an input parameter N. In other words there will be N numbers on the bottom layer of the pyramid.

The Pyramid construction rules are as follows

- First number in the series should be at the top of the Pyramid
- Last N number of the series should be on the bottom-most layer of the Pyramid, with N
^{th}number being the right-most number of this layer. - Numbers less than 5-digits must be padded with zeroes to maintain the sanctity of a Pyramid when printed. Have a look at the examples below to get a pictorial understanding of what this rule actually means.

Example

** If input is 2, output will be**00006

00028 00066

**00006**

**If input is 3, output will be**

00028 00066

00120 00190 00276

Formal input and output specifications are stated below

**Input Format:**

- First line of input will contain number N that corresponds to the width of the bottom-most layer of the Pyramid

**Output Format:**

- The Pyramid constructed out of numbers in the series as per stated construction rules

**Constraints:**

- 0 < N <= 14

**PROGRAM**

**Java Program**

import java.util.Scanner; public class Main { public static void main (String[]args) { int n, a = 0, b = 3, i, re, j; Scanner sc = new Scanner (System.in); n = sc.nextInt (); for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { a = a + 2; if (i == 1) b = 3; else b = b + 4; re = a * b; System.out.println (re); } System.out.println (); } } }

**Python Program**

n=int(input()) a,b=0,3 for i in range(1,n+1): for j in range(1,i+1): a=a+2 if(i==1):b=3 else:b=b+4 re=a*b print("%.5d"%(re),end=" ") print()

**Questions) ****Problem Statement:- **Hobo’s Drawing teacher asks his class to open their books to a page number. Hobo can either start turning pages from the front of the book or from the back of the book. He always turns pages one at a time. When she opens the book, page 1 is always on the right side: When he flips page 1, he sees pages 2 and 3. Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is n pages long, and he wants to turn to page p, what is the minimum number of pages he will turn? He can start at the beginning or the end of the book. Given n and p, find and print the minimum number of pages Hobo must turn in order to arrive at page p

**Function Description**

Complete the *countpage *function in the editor below. It should return the minimum number of pages Hobo must turn.

*countpage *has the following parameter(s):

*n*: the number of pages in the book*p*: the page number to turn to

**Input Format**

- The first line contains an integer n, the number of pages in the book.
- The second line contains an integer, p, the page that Hobo’s teacher wants her to turn to.

**Output Format**

- Print an integer denoting the minimum number of pages Hobo must turn to get to page p

**Sample Input
**6

2

**Sample Output
**1

**PROGRAM**

**C++ Program**

#include <iostream> using namespace std; int main() { int n=0,p=0,min; cin >> n; cin >> p; min=(n/2)-(p/2); if(min>p/2) min=p/2; cout << min; return 0; }

**JAVA Program**

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int p = sc.nextInt(); System.out.println(Math.min(p/2, n/2 - p/2)); } }

**Questions) ****Problem Statement-:**One person hands over the list of digits to Mr. String, But Mr. String understands only strings. Within strings also he understands only vowels. Mr. String needs your help to find the total number of pairs that add up to a certain digit D.

The rules to calculate digit D are as follows

- Take all digits and convert them into their textual representation
- Next, sum up the number of vowels i.e. {a, e, i, o, u} from all textual representation
- This sum is digit D

Now, once digit D is known find out all unordered pairs of numbers in input whose sum is equal to D. Refer example section for better understanding.

### Constraints

- 1 <= N <= 100
- 1 <= value of each element in second line of input <= 100

Number 100, if and when it appears in the input should be converted to textual representation as a hundred and not as one hundred. Hence the number of vowels in the number 100 should be 2 and not 4

### Input

- the First line contains an integer N which represents the number of elements to be processed as input
- the Second line contains N numbers separated by space

### Output

- Lower case representation of a textual representation of the number of pairs in input that sum up to digit D

Note: – (If the count exceeds 100 print “greater 100”)

### Time Limit

1

### Examples

**Example 1**

**Input
**5

1 2 3 4 5

**Output
**one

**Explanation
**1 -> one -> o, e

2 -> two -> o

3 -> three -> e, e

4 -> four -> o, u

5 -> five – > i, e

Thus, count of vowels in textual representation of numbers in input = {2 + 1 + 2 + 2 + 2} = 9. Number 9 is the digit D referred to in the section above.

Now from the given list of numbers {1,2,3,4,5} -> find all pairs that sum up to 9.

Upon processing this we know that only a single unordered pair {4, 5} sum up to 9. Hence the answer is 1. However, output specification requires you to print textual representation of number 1 which is one. Hence the output is one.

Note: – Pairs {4, 5} or {5, 4} both sum up to 9. But since we are asking to count only unordered pairs, the number of unordered pairs in this combination is only one.

**Example 2**

**Input
**3

7 4 2

**Output
**zero

**Explanation
**7 -> seven -> e, e

4 -> four -> o, u

2 -> two -> o

Thus, count of vowels in textual representation of numbers in input = {2 + 2 + 1} = 5. Number 5 is the digit D referred to in the section above.

Since no pairs add up to 5, the answer is 0. The textual representation of 0 is zero. Hence the output is zero.

**PROGRAM**

**Python Program**

k = [''] * 101 k[0] = "zero" k[1] = "one" k[2] = "two" k[3] = "three" k[4] = "four" k[5] = "five" k[6] = "six" k[7] = "seven" k[8] = "eight" k[9] = "nine" k[10] = "ten" k[11] = "eleven" k[12] = "twelve" k[13] = "thirteen" k[14] = "fourteen" k[15] = "fifteen" k[20] = "twenty" k[30] = "thirty" k[40] = "forty" k[50] = "fifty" k[80] = "eighty" k[100] = "hundred" def vowel(str): s = 0 for i in str: if i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u': s += 1 return s def findword(a): if k[a] != "": return k[a] elif 20 > a > 15: k[a] = k[a % 10] + "teen" return k[a] elif a > 100: print("Wrong Input") return 0 else: k[a] = k[(a // 10) * 10] + "-" + k[a % 10] return k[a] sum1 = 0 sum2 = 0 n = int(input()) a = list(map(int, input().split())) for i in range(n): sum1 += vowel(findword(a[i])) for i in range(n - 1): for j in range(i + 1, n): if a[i] + a[j] == sum1: sum2 += 1 print(findword(sum2))

**Java Program**

import java.util.*; class Main { static String arr[] = new String[101]; public static int vowel (String str) { int sum = 0; for (int i = 0; i < str.length (); i++) if (str.charAt (i) == 'a' || str.charAt (i) == 'e'|| str.charAt (i) == 'i' || str.charAt (i) == 'o'|| str.charAt (i) == 'u') sum += 1; return sum; } public static String findWord (int no) { if (no <= 15) return arr[no]; if (no < 20 && no > 15) { arr[no] = arr[no % 10] + "teen"; return arr[no]; } if (no % 10 == 0) { arr[no] = arr[no / 10] + "ty"; return arr[no]; } if (no > 100) return "greater 100"; arr[no] = arr[(no / 10) * 10] + "-" + arr[no % 10]; return arr[no]; } public static void main (String[]args) { for (int i = 0; i < 100; i++) arr[i] = ""; arr[0] = "zero"; arr[1] = "one"; arr[2] = "two"; arr[3] = "three"; arr[4] = "four"; arr[5] = "five"; arr[6] = "six"; arr[7] = "seven"; arr[8] = "eight"; arr[9] = "nine"; arr[10] = "ten"; arr[11] = "eleven"; arr[12] = "twelve"; arr[13] = "thirteen"; arr[14] = "fourteen"; arr[15] = "fifteen"; arr[20] = "twenty"; arr[30] = "thirty"; arr[40] = "forty"; arr[50] = "fifty"; arr[60] = "sixty"; arr[70] = "seventy"; arr[80] = "eighty"; arr[90] = "ninenty"; arr[100] = "hundred"; int sum1 = 0; int sum2 = 0; Scanner sc = new Scanner (System.in); int n = sc.nextInt (); int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt (); for (int i = 0; i < n; i++) sum1 += vowel (findWord (a[i])); for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == sum1) sum2 += 1; System.out.println (findWord (sum2)); } }

**Questions) ****Problem Statement:- **A jail has several prisoners and several treats to pass out to them. Their jailer decides the fairest way to divide the treats is to seat the prisoners around a circular table in sequentially numbered chairs. A chair number will be drawn from a hat. Beginning with the prisoner in that chair, one candy will be handed to each prisoner sequentially around the table until all have been distributed.

The jailer is playing a little joke, though. The last piece of candy looks like all the others, but it tastes *awful*. Determine the chair number occupied by the prisoner who will receive that candy.

For example, there are 4 prisoners and 6 pieces of candy. The prisoners arrange themselves in seats numbered 1 to 4. Let’s suppose two are drawn from the hat. Prisoners receive candy at positions 2,3,4,1,2,3. The prisoner to be warned sits in chair number 3

**Function Description**

Write a function to *save the prisoner*. It should return an integer representing the chair number of the prisoner to warn.

*save the prisoner* has the following parameter(s):

*n*: an integer, the number of prisoners*m*: an integer, the number of sweets*s*: an integer, the chair number to begin passing out sweets from

**Input Format**

- The first line contains an integer t, denoting the number of test cases.
- The next t lines each contain 3 space-separated integers:
- -: n the number of prisoners
- -: m the number of sweets
- -: s the chair number to start passing out treats at

**Output Format**

- For each test case, print the chair number of the prisoner who receives the
*awful treat*on a new line.

**Sample
**2

5 2 1

5 2 2

**Sample Output
**2

3

**PROGRAM**

**C Program**

#include <stdio.h> int main() { int t,j,i,count=0; long int ncr; long int result,diff; scanf("%d",&t); long int n[t]; long int m[t]; long int s[t]; for(i=0;i<t;i++) {="" scanf("%ld="" %ld="" %ld",&n[i],&m[i],&s[i]);="" }="" for(i="0;i<t;i++)" count="(n[i]-s[i])+1;" if(count="">=m[i]) { result=(s[i]+m[i])-1; printf("%ld\n",result); } if(count<m[i]) {="" diff="m[i]-count;" while(diff="">n[i]) { diff=diff-n[i]; } printf("%ld\n",diff); } } return 0; }</m[i])></t;i++)>

**JAVA Program**

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); int arr[] = new int [T]; int i = 0; while (T-- > 0) { int N = scan.nextInt(); int M = scan.nextInt(); int S = scan.nextInt(); int last = ((M - 1) + (S - 1)) % N + 1; arr[i] = last; i+=1; } scan.close(); for(int z=0;z<arr.length;z++) { System.out.println(arr[z]); } } }

**Questions) Problem Statement:- **You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value.

For example, given an array of [1, 2, 3, 4] and a target value of 1, we have three values meeting the condition: 2-1 = 1, 3-2 = 1, and 4-3 = 1.

**Function Description**

Write a function *pairs*. It must return an integer representing the number of element pairs having the required difference.

Pairs has the following parameter(s):

*k*: an integer, the target difference*arr*: an array of integers

**Input Format**

- The first line contains two space-separated integers n and k, the size of arr and the target value.
- The second line contains n space-separated integers of the array arr.

**Sample Input
**5 2

1 5 3 4 2

**Sample Output
**3

**PROGRAM**

**C Program**

#include <stdio.h> int countPairsWithDiffK(int arr[], int n, int k) { int count = 0; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { if (arr[i] - arr[j] == k || arr[j] - arr[i] == k ) { count++; } } } return count; } int main() { int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3, result; result = countPairsWithDiffK(arr, n, k); printf("%d",result); return 0; }

**Python Program**

def pairs(k, arr): q = 0 n = len(arr) arr = set(arr) h = len(arr) - n for i in arr: if i+k in arr: q+=1 return q+h nk = input().split() n = int(nk[0]) k = int(nk[1]) arr = list(map(int, input().rstrip().split())) result = pairs(k, arr) print(result)

**Questions) **Radha is attending her sister’s wedding, and there are a lot of things to do including packing and food and decorating. Radha took up the responsibility for packing the sweets, as no one was interested in doing such tedious work. She got an idea, where she announced that we will pick a winner from a packing contest, and those who win this game will be given a surprise gift. The best part is that more than 1 person can be the winner in this game.

Radha, by default, is the first player. So, the game goes like this:

- All the sweet boxes are represented with numbers, to differentiate them from each other. Let us say that a box numbered ‘1’ will contain a different sweet compared to the one which is numbered ‘2’.
- Each player will be given different/same combinations of sweets boxes in different/same quantities.
- Each player has to pack all the respective boxes given to them, in one final package.
- As a default point, each person will be given the number of points equal to the number of boxes they pack. Let us say they have 6 sweet boxes in their queue, they will get 6 points as default.
- If the final package contains 4 different types of sweets, then they will get an additional 1 point.
- If the final package contains 5 different types of sweets, then they will get additional 2 points.
- If the final package contains 6 or more different types of sweets, then they will get additional 4 points.

Radha is Player 1, and the remaining players follow after that. The input will be in the format given below:

**For Player-1** (Radha):

1

6 1 2 3 4 5 7

This means there is only 1 player, and 6 is the number of boxes given to her. And the remaining values (1 2 3 4 5 7).

If we have multiple participants then, say we have 3 participants

3

6 1 2 3 4 5

4 1 3 2 2

5 1 2 2 3 3

This means we have 3 participants (N=3)

**First participant:**

- Number of boxes 6, N = Z[0]
- The types of sweets in these 6 boxes are, respectively, as 1 2 3 4 5 7, 1.e., Z[1, N]

**Second participant:**

- Number of boxes 4, N = Z[0]
- The types of sweets in these 6 boxes are, respectively, as 1 3 2 2, i.e., Z[1, N]

**Third participant:**

- Number of boxes 5, N = Z[0]
- The types of sweets in these 6 boxes are respectively, as 1 2 2 3 3 i.e., Z[1, N]

**Your output will be:
**

**Radha:**If Radha wins.

**Tie:**If 2 or more 2 players have the same score.

**A[i]:**Index of the player.

**Example 1:**

**Input:**

2 -> Input string. Integer N.

6 1 2 3 4 5 6-> Input Integer, Z[ ]

9 3 3 3 4 4 4 5 5 5 -> Input integer, Z[ ]**Output:**

Radha -> Output**Explanation:**From the above inputs let’s calculate the total points for each player.

**Player 1:**Radha

Has 6 boxes, so 6 points in the beginning.

She has 6 different types of sweets (from 1-6), hence 6 more points to that.

Total of 6 + 6 = 12 points**Player 2:**Has 9 boxes, so 9 points in the beginning.

She has only 3 different types of sweets (3,4 & 5), so no points to that.

Total of 9 points.

Radha is a winner with more points.

**Example 2:**

**Input:**

2 -> Input string. Integer N.

3 1 2 3 -> Input Integer, A[ ], Z[ ].

4 1 2 3 4 -> Input integer, A[ ], Z[ ].**Output:**

2 -> Output**Explanation:**

From the above inputs let’s calculate the total points for each player:**Player 1:**Radha

Has 3 boxes, so 3 points in the beginning.

She has 3 different types of sweets (from 1-3), so no points to that.

Total of 3 points.**Player 2:**Has 4 boxes, so 4 points in the beginning.

She has only 3 different types of sweets (1 – 4), so 1 point to that.

Total of 3+1 = 4 points.

Player 2 is a winner with more points. So, the answer is 2.

**PROGRAM**

def find(l1): length = len(l1) finalans = l1[0] l1.pop(0) setl1 = set(l1) if len(setl1) == 6: finalans += 4 elif len(setl1) == 4: finalans += 1 elif len(setl1) == 5: finalans += 2 finalans += sum(setl1) return finalans n = int(input()) final = [] for i in range(n): l1 = list(map(int, input().split())) finalSum = find(l1) final.append(finalSum) maximum = max(final) countofMax = final.count(maximum) if countofMax == 1: if final[0] == maximum: print("Radha") else: print(final.index(maximum)) else: for i in final: if i == maximum: print(i + 2, end=" ")

**Questions) **King Jeremy’s family has ruled a kingdom for N consecutive years numbered from 1 to N. The year i is described by a prosperity value A[i]. This is a positive integer when there was prosperity in the year and a negative integer when it was a difficult year for the kingdom. A historical period is described with two integers, S and F as [S, F], i.e. [Start, Finish], where S and F are from 1 to N, S <= F.

The target is to pick 2 historical periods, with the following 6 conditions:

- The two periods shouldn’t have common years. For example (1,5) has no common year with [6,7).
- the First period should start earlier than the second one, 1.e. (1,5) should be the first period, and then the [6,7] should start.
- There should be a difference of more than K integers between the Finish of the first period and the start of the 2nd period.
- Sum of prosperity values for the years in the periods chosen should be as large as possible.

Given N, A[ ], and K, give this maximum prosperity value as output.

E.g.

N = 5, number of years

K = 3, difference between 2 periods.

A = {-1, 1, 2, 3, -1} prosperity value for each year.

There is only 1 way to choose the two periods, which is [1,1] and [5,5) as the difference has to be greater than 3 (value of K).

The prosperity values for these are

[1, 1] = -1

[5, 5] = -1

The Some of these values are -2. Hence, the answer is -2.

**Example 1:**

**Input:**

8 -> Input Integer, N

3 -> Input Integer, K

{5, 5, -1, -2, 3, -1, 2, -2} -> Input sequence, A[ ].**Output:**

12 -> Output**Explanation:**

In the above case: N equals to 8, K equals to 3, Al equals to {5, 5,-1,-2,3,-1, 2, -2}. It is optimal to choose [1, 2] and [7, 7) periods. That is the only optimal choice that you can make.

So the values will be

[1, 2] = 5 5

[7, 7] = 2

The sum of it will be 5 + 5 + 2 = 12

**Example 2:**

**Input:**

6 -> Input Integer, N

0 -> input Integer, K

{5, -1, 5, 0, -1, 9} -> Input sequence A[ ].**Output:**

18 -> Output**Explanation:**

In the above case: N equals 6, and K equals to 0. All equals to {5,-1,5, 0, 1,9}. It is optimal to choose [1, 3] and [6, 6] periods. But that is not the only optimal choice that you can make So the values will be

[1, 3] = 5 – 1 5

[6, 6] = 9The sum of it will be 5 -1+5+9 = 18.

**PROGRAM**

n = int(input()) k = int(input()) A = list(map(int, input().split())) final = [] for i in range(1, n + 1): for j in range(1, n + 1): if j >= i: final.append([i, j]) maximum = 0 for i in range(len(final)): for j in range(len(final)): if i != j: a = [i for i in range(final[i][0], final[i][1] + 1)] b = [i for i in range(final[j][0], final[j][1] + 1)] if len(set(a).intersection(set(b))) == 0: if final[i][1] < final[j][0]: ans = final[j][0] - final[i][1] if ans > k: sumvalue = 0 for p in range(((final[i][0]) - 1), final[i][1]): sumvalue += A[p] for p in range(((final[j][0]) - 1), final[j][1]): sumvalue += A[p] maximum = max(maximum, sumvalue) print(maximum)

**Questions) **Alice has introduced a new online game which has N levels i e., 1 to N. She wants to get reviews for each level of this game so she will launch only a single level of game on any particular day, and on that day users of this game are allowed to play only that particular level. As there are N levels so it will take exactly N days to launch all levels of the game, it is not necessary that level of game will be launched in increasing order, she will pick any random level on particular day and launch it, and it is obvious that any level of the game can’t be launched twice. After completing the level, the user will give reviews and she will give them one reward unit for each level the user will complete. Alice has put one constraint on users that only after completing any level of game, user will be able to play higher levels. For E.g. If Alice has launched the 3rd level of the game on the first day and if any user completes it then he will get one reward point, but now. he can’t play the game with level 1 and level 2.

**NOTE:** If a user wants to skip to play on any number of days, he is free to do that.

You are the best gamer, so you can easily complete all levels. As you want to maximize your reward points, you want to play as many levels as you can. Alice has already announced the order in which she will launch levels of his game, your aim is to maximize your reward points.

Given number of levels of games(N) and order of level of games launched one by one on each day. You have to output maximum reward points you can earn.

**Hint:** You will play any game if and only if that number is becoming the part of the longest subsequence in array of order of games.

**Example 1:**

**Input:**

5 -> N = 5

2 1 3 4 5 -> Order of levels, Alice will launch one by one**Output:**

4**Explanation:**

If you play the 2nd level of the game on the first day, then you will not be able to play the 1st level of the game on the 2nd day. As after completing the 2nd level, you will be able to play higher levels. From 3rd day you can play all upcoming levels as those levels are in increasing order. So, possible sequences of levels of games played to maximize rewards points are [2, 3, 4, 5] or [1, 3, 4, 5]. In both cases you will get 4 reward points.

**Example 2:**

**Input:**

5 -> N = 5

5 4 3 2 1 -> Order of levels, Alice will launch one by one**Output:**

1**Explanation:**

Alice has launched levels in decreasing order, so you will be able to play exactly one level of game. After playing any level, there are no higher levels on coming days, so maximum reward point is 1.

**PROGRAM:**

def fun(n, arr): if arr == sorted(arr, reverse=True): return 1 if arr == sorted(arr): return n ans = 1 for i in range(n - 1): m = 1 for j in range(i + 1, n): if arr[j] > arr[i]: m += 1 ans = max(m, ans) return ans N = int(input()) ar = list(map(int, input().split())) print(fun(N, ar))

**Questions)** You are given an array A of size N. Your friend gave me an amazıng task for you. Your friend likes one type of Sequence. So, he called that type of sequence a fair sequence. You should select a fair sequence of maximum length from an array. Here a fair sequence is nothing but you have to select elements in a pattern like positive element, negative element, positive element… (negative element, positive element, negative element, to form a sequence.

Your task is to print the maximum sum of elements possible by selecting a fair subsequence with maximum length.

**Ex:** If art A = [-1, 18, 13, 18, 2, 16,7,-1, -213, 11]. Here your minimum length can be which subsequences -7 -2, 7,-1, 11. The sum is 27,-1, which is the maximum Your friend also kept a timer of 15 min. If you can solve. Your task is to print the maximum sum of elements possible by selecting a fair subsequence with maximum length.

**Ex:** If array A = [-1, 18, 13, 18, 2, 16,7,-1, -213, 11]. Here your minimum length can be 6. The fair subsequence is -1, -18,-7, -2, 7,-1, 11. The Sum is 32 which is the maximum possible. Your friend also kept a timer of 15 min. You will win, will you be able to do it?

**NOTE:** You should select the elements in a fair sequence only.

**Example – 1:**

**Input:**5 – N ( Number of elements in an array )

21 12 13 -21 -2 – Array A consists of N elements**Output:**

19**Explanation:**

Here you can select 21, -2 subsequences of maximum length 2. The sum is 19 which is the maximum possible for a fair subsequence of length 2.

**Example – 2:**

**Input:**

-153 -689**Output:**

-153**Explanation:**

Here you can select 21, -2 subsequences of maximum length 2. The sum is 19 which is the maximum possible for a fair subsequence of length 2.

**PROGRAM**

def fun(arr, n): ans = [] t = 1 if arr[0] > 0: t = 0 i = 0 while i < n: if t == 0: j = i while j < n: if arr[j] > 0: j += 1 else: break ans.append(max(arr[i:j])) i = j t = 1 else: j = i while j < n: if arr[j] < 0: j += 1 else: break ans.append(max(arr[i:j])) i = j t = 0 return sum(ans) n = int(input()) ar = list(map(int, input().split())) print(fun(ar, n))

Important Details |
---|