CodeVita Menu9>
- PrepInsta Home
- TCS CodeVita
- TCS CodeVita Previous Year Questions and Answers
- TCS CodeVita Syllabus
- TCS CodeVita Coding Questions
- TCS CodeVita Registration
- How To Prepare
- TCS CodeVita Exam Date
- Eligibility Criteria
- Interview Experiences
- Get Off-campus Hiring Updates
- Get Hiring Updates
- Contact us
- Prime Video
PREPINSTA PRIME
TCS CodeVita Coding Questions
TCS CodeVita Coding Questions with Solutions
TCS CodeVita Season 11 is the eleventh edition of the prestigious coding competition TCS CodeVita which is organized by TCS every year, in the search of world’s best coder. TCS CodeVita is a global level coding competition, in which participants from all over the world compete for the title of “World’s Best Coder” and a prize money of 20,000 US$. On this page, TCS CodeVita Coding Questions are given which help you to prepare for TCS CodeVita.
Go through TCS CodeVita Coding Questions page to practice Coding Questions for TCS CodeVita.
TCS CodeVita Coding Questions with Solutions
Civil War
Problem Description
In this superhero epic, the denizens of the Marvel Universe are forced to pick sides when Captain America and Iron Man come to blows over ideological differences.
The government decides to push for the Hero Registration Act, a law that limits a hero’s actions. This results in a division in The Avengers. Iron Man stands with this Act, claiming that their actions must be kept in check otherwise cities will continue to be destroyed, but Captain America feels that saving the world is daring enough and that they cannot rely on the government to protect the world. And here the civil war begins.
They are trying make their team stronger by adding more avengers to their team. There are N avengers lined up.
Rules to add avenger to their team-
- Any team can start first. But they will alternatively only.
- They can select avenger from any side. But if they start from one side they can’t move to other side in current chance.
- They can select consecutive avengers as many they want.
- They will stop only when all the avengers are part of either side.
- Every Avenger has a power associated with him
- There are some spurious avengers who will decrease the overall power of the team.
Both teams will select players optimally. Find the difference of powers of the two teams
Constraints
1<= N <= 10^6
-10^9 <= p[i] <= 10^9
Input
First line contains an integer denoting the number of Avengers(N).
Next lines contain N space separated values denoting power of every avenger(P[i]).
Output
Print the difference of the powers of teams
– Time Limit (secs)
1
Examples :
Input
5
2-78-1 20
Output
2
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Use Coupon Code “CT10” and get a flat 10% OFF on your Prime plus one month extension on 12 months and above plans.
#include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; vector powers(N); for (int i = 0; i < N; i++) { cin >> powers[i]; } int teamAPower = 0; int teamBPower = 0; sort(powers.begin(), powers.end(), [](int a, int b) { return abs(a) > abs(b) || (abs(a) == abs(b) && a > b); }); bool ironmanTurn = true; for (int i = 0; i < N; i++) { if (ironmanTurn) { teamAPower += powers[i]; } else { teamBPower += powers[i]; } ironmanTurn = !ironmanTurn; } int powerDifference = abs(teamAPower - teamBPower); cout << powerDifference << endl; return 0; }
import java.util.*;public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); List powers = new ArrayList<>();
for (int i = 0; i < N; i++) { powers.add(scanner.nextInt()); }
int teamAPower = 0; int teamBPower = 0; // Sort the powers Collections.sort(powers, new Comparator() { @Override public int compare(Integer a, Integer b) { int absA = Math.abs(a); int absB = Math.abs(b); if (absA == absB) { return Integer.compare(b, a); // Invert order if absolute values are equal } return Integer.compare(absB, absA); } }); boolean ironmanTurn = true; for (int i = 0; i < N; i++) { if (ironmanTurn) { teamAPower += powers.get(i); } else { teamBPower += powers.get(i); } ironmanTurn = !ironmanTurn; } int powerDifference = Math.abs(teamAPower - teamBPower); System.out.println(powerDifference); } }
</div
N = int(input()) powers = list(map(int, input().split())) team_a_power = 0 team_b_power = 0 # Sort the powers powers.sort(key=lambda x: (abs(x), -x), reverse=True) # Assign Avengers to teams alternatively ironman_turn = True for power in powers: if ironman_turn: team_a_power += power else: team_b_power += power ironman_turn = not ironman_turn power_difference = abs(team_a_power - team_b_power) print(power_difference)
Encryption
Problem Description
John is working in high security organization, where he needs to deal with lot of confidential documents. He must encrypt the important number in documents. Please help John to write a program where the system should identify the integer number and encrypt number based on John’s actions.
John’s actions are as follows
Actions | Denoted by | Remarks |
---|---|---|
Right arrow | R | Move to next character |
Left arrow | T | Move to previous character |
Up arrow | L | Increment the integer by one |
Down arrow | D | Decrement the integer by one |
Swap | Sn | Swap the current position with number in the nth position |
These actions are governed by the rules mentioned below.
Rules
- Initial position is at the first character of the string comprised of numbers.
- When incrementing the value of a number at a current location, if the number is 9 then it remains 9 else it increases by 1.
- When decrementing the value of a number at a current location, if the number is 0 then it remains O else it decreases by 1.
- Once all the actions from the action string are consumed, if any part of the input string remained unprocessed then leave those characters of the input string as they are.
Constraints
0 <n<= I where I is length of the input string.
Input
First line contains a string comprising of numbers. This is referred to as input string in the rest of the document.
Second line contains the actions denoted by values mentioned in the table above. This is referred to as action string in the rest of the document.
Output
Single string comprising of numbers.
Time Limit (secs)
1
Examples
Input
123456
RLTDRRTRS2S1
Output
244156
Explanation
Initial string: 123456
Action: RLTDRRTRS2S1
R: 1[2]3456
L: [1]23456
T: [2]23456
D: [1]23456
R: 1[2]3456
R: 12[3]456
T:12[4]456
R: 124[4]56
S2: 144[2]56
S1: 244[1]56
output string.
Since all the actions from the action string are consumed and only first four characters of the input string are processed leave the last two as they are and make them the part of
#include< bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; string s; cin>>s; int i=0; string a = to_string(n); int j =0; for(int i=0;i< s.size();i++){ if(s[i] == 'R') j= j+1; else if(s[i] == 'L') j = j-1; else if(s[i] == 'T') (int)a[j]++; else if(s[i] == 'D') (int)a[i]--; else{ swap(a[s[i]], a[s[i+1]]); i++; } } cout<< a; }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String s = scanner.next(); int i = 0; String a = Integer.toString(n); int j = 0; for (int k = 0; k < s.length(); k++) { if (s.charAt(k) == 'R') { j = j + 1; } else if (s.charAt(k) == 'L') { j = j - 1; } else if (s.charAt(k) == 'T') { a = a.substring(0, j) + (char)(a.charAt(j) + 1) + a.substring(j + 1); } else if (s.charAt(k) == 'D') { a = a.substring(0, i) + (char)(a.charAt(i) - 1) + a.substring(i + 1); } else { char temp = a.charAt(s.charAt(k)); a = a.substring(0, s.charAt(k)) + a.charAt(s.charAt(k + 1)) + a.substring(s.charAt(k) + 2); a = a.substring(0, s.charAt(k + 1)) + temp + a.substring(s.charAt(k + 1) + 1); k++; } } System.out.println(a); } }
n = int(input()) s = input() i = 0 a = str(n) j = 0 for i in range(len(s)): if s[i] == 'R': j = j + 1 elif s[i] == 'L': j = j - 1 elif s[i] == 'U': a = a[:j] + str((int(a[j]) + 1) % 10) + a[j+1:] elif s[i] == 'D': a = a[:j] + str((int(a[j]) - 1) % 10) + a[j+1:] else: a = list(a) a[s[i]], a[s[i+1]] = a[s[i+1]], a[s[i]] a = ''.join(a) print(a)
Possible Legal Subsets
Problem Description
You are given N comma-separated Strings. You need to form all possible legal subsets of these N strings. These subsets will be a combination of zero or more of these N Strings After forming the subsets, they will be ranked in a particular onder. The legal subset formation and ranking logic is as described below
- Rank 1 will always be an empty set
- Next N ranks will be the N Strings that appear in the order they are provided in the input
- After N + 1 ranks, you need to combine N strings such that all legal combinations are formed
- Legal combination simply means that while combinations are formed, the string that appears to the left of a particular string in the input, can never appear to the right of that particular string, when subsets are formed
- A subset with less elements will be ranked higher than a subset with more elements (NOTE-Rank 1 is higher than rank 2)
- Refer Example 2 to get a better understanding of how subsets are formed and ranked
- It is guaranteed that
- N>=1
- All N strings are unique
Example: you are having an input string “aa,cc,bb” in this string we can see we have three strings which are comma separated. Now from this group of string we have to create all possible subset of strings. 8 subsets can be formed from these strings. And they are as follows:
- {}
- {aa}
- {cc}
- {bb}
- {aa,}
Note: here we can see the ranks given to the subsets are first by size i.e., the subset with lesser number of strings is ranked higher than the subset with higher size. If the subsets have equal number of strings then, the combination which is formed earlier (by virtue of combining strings in order they appear in input), gets a higher rank.
For example, rank of su bset (aa,cc) > rank of (aa,bb) because string cc is appearing prior to string bb in the input. Similarly, rank of (cc) > rank of (bb).
You are provided one rank R and for that you have to print the Rth subset from all legal subsets.
Constraints:
0<N<=10^2
0<R<=10^18
Input
First line contains an integer N which is number of strings in group.
Second line contains an integer R, for which you have to find Rth subset from all legal subsets.
Third line contains N comma-separated strings basis which the subsets should be formed
Output:
From all possible legal subsets find the subset whose rank is R
Time Limit (secs)
1
Input
2
4
a,b
Output
a,b
Explanation:
Given that N = 2, given
Second line: Rank to be find: 4th
Third line: Given group of strings: a,b
Possible subsets & Rank
{}-1
{a} -2
{b}-3
{a, b}-4
Output – a,b (4th rank corresponds to a,b)
#include<bits/stdc++.h> using namespace std; vector find_subsets(int N, long long R, string strings) { vector subsets; subsets.push_back(""); // Rank 1: Empty set // Split input strings into a vector vector strings_list; size_t pos = 0; while ((pos = strings.find(',')) != string::npos) { strings_list.push_back(strings.substr(0, pos)); strings.erase(0, pos + 1); } strings_list.push_back(strings); // Add the last string // Add individual strings as subsets with ranks 2 to N + 1 for (const string& s : strings_list) { subsets.push_back(s); } // Generate subsets with combinations of strings for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { string subset = strings_list[i] + "," + strings_list[j]; // Check if this subset is legal bool legal = true; for (int k = j + 1; k < N; ++k) { size_t pos1 = subset.find(strings_list[k]); size_t pos2 = subset.find(",", pos1); if (pos1 != string::npos && pos2 == string::npos) { legal = false; break; } } // If legal, add it to the subsets if (legal) { subsets.push_back(subset); } } } // Sort subsets based on size and order of appearance sort(subsets.begin(), subsets.end(), [](const string& a, const string& b) { if (a.size() == b.size()) { for (int i = 0; i < a.size(); ++i) { if (a[i] != b[i]) { return a[i] < b[i]; } } } return a.size() < b.size(); }); // Return the Rth subset vector result; result.push_back(subsets[R - 1]); return result; } int main() { int N; long long R; string strings; // Read input values cin >> N >> R; cin.ignore(); // Ignore the newline character after R getline(cin, strings); // Find the Rth subset vector result = find_subsets(N, R, strings); // Output the Rth subset cout << result[0]; return 0; }
import java.util.*; public class SubsetRank { public static List findSubsets(int N, long R, String strings) { List subsets = new ArrayList<>(); subsets.add(""); // Rank 1: Empty set // Split input strings into a list List stringsList = Arrays.asList(strings.split(",")); // Add individual strings as subsets with ranks 2 to N + 1 subsets.addAll(stringsList); // Generate subsets with combinations of strings for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { String subset = stringsList.get(i) + "," + stringsList.get(j); // Check if this subset is legal boolean legal = true; for (int k = j + 1; k < N; ++k) { int pos1 = subset.indexOf(stringsList.get(k)); int pos2 = subset.indexOf(",", pos1); if (pos1 != -1 && pos2 == -1) { legal = false; break; } } // If legal, add it to the subsets if (legal) { subsets.add(subset); } } } // Sort subsets based on size and order of appearance subsets.sort(Comparator.comparingInt(String::length).thenComparing(subset -> { List items = Arrays.asList(subset.split(",")); return stringsList.indexOf(items.get(0)); })); // Return the Rth subset List result = new ArrayList<>(); result.add(subsets.get((int) R - 1)); return result; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); long R = scanner.nextLong(); scanner.nextLine(); // Consume the newline character String strings = scanner.nextLine(); // Find the Rth subset List result = findSubsets(N, R, strings); // Output the Rth subset System.out.println(result.get(0)); } }
Use Coupon Code “CT10” and get a flat 10% OFF on your Prime plus one month extension on 12 months and above plans.
Seating Arrangement
Problem Description
You are a caretaker of a waiting room and you have to take care of empty seats such that all the people should sit together. Imagine the seats are in a straight line like in a movie theatre. People are seated on random seats initially. Your task is to make them sit together so that minimum number of people change their position. Also, they can be made to sit together in many ways. Find the number of ways you can make them sit together by requiring only minimal people movement.
“E” depicts an empty seat and “O” depicts an occupied seat. Input will be given in the form of a string.
Example: OEOEO
As we can see, only seat number 1, 3, 5 are occupied and 2 and 4 are empty.
Case 1: If we move 5th person to 2nd position, they can all be together with only one person moving his/her place.
Case 2: If we movement 1st person to 4th position, they can all be together with only one person moving his/her place.
They can all be together with only one movement and this can be done in 2 ways. Print the minimum number of movements required and the number of ways this minimum movement can help achieve the objective.
Note: If they are already sitting together, Print “00” as output.
Constraints
0 <N <= 100000
Input
First line contains an integer N which depicts the number of seats
Second line contains N characters each of which are either “O” or “E”. “O” denotes an occupied seat and “E” denotes an empty seat.
Output
Print minimum number of movements required and the number of ways in which all people can be made to sit together without exceeding minimum number of movements by space
Time Limit (secs)
1
Examples
Input
5
OEOEO
Output
1 2
Explanation:
Given data of 5 seats in the queue,
Seat number 2 and 4 are unoccupied and all the other seats are occupied.
We can make them sit together by moving only one person near to the other. It can be done in 2 ways:
OOOEE (Moving 4 person to 2º position)
EE000 (Moving 1 person to 4 position)
#include<bits/stdc++.h> using namespace std; pair< int, int> min_moves_together(string seats) { int occupied = count(seats.begin(), seats.end(), 'O'); if (occupied == 0 || occupied == seats.length()) { return make_pair(0, 0); } vector< int> empty_counts; int current_available = 0; for (char seat : seats) { if (seat == 'E') { current_available += 1; } else { if (current_available > 0) { empty_counts.push_back(current_available); } current_available = 0; } } int min_empty_seats = *min_element(empty_counts.begin(), empty_counts.end()); int min_moves = min_empty_seats - 1; int ways = count(empty_counts.begin(), empty_counts.end(), min_empty_seats); return make_pair(min_moves * occupied +1, ways); } int main() { int N; cin >> N; string seats; cin >> seats; pair<int, int> result = min_moves_together(seats); cout << result.first << " " << result.second << endl; return 0; }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); String seats = scanner.next(); int[] result = minMovesTogether(seats); System.out.println(result[0] + " " + result[1]); } public static int[] minMovesTogether(String seats) { int occupied = 0; for (char seat : seats.toCharArray()) { if (seat == 'O') { occupied++; } } if (occupied == 0 || occupied == seats.length()) { return new int[]{0, 0}; } int[] emptyCounts = new int[seats.length()]; int currentAvailable = 0; int index = 0; for (char seat : seats.toCharArray()) { if (seat == 'E') { currentAvailable++; } else { if (currentAvailable > 0) { emptyCounts[index++] = currentAvailable; } currentAvailable = 0; } } int minEmptySeats = Integer.MAX_VALUE; for (int i = 0; i < index; i++) { minEmptySeats = Math.min(minEmptySeats, emptyCounts[i]); } int minMoves = minEmptySeats - 1; int ways = 0; for (int i = 0; i < index; i++) { if (emptyCounts[i] == minEmptySeats) { ways++; } } return new int[]{minMoves * occupied+1, ways}; } }
def min_moves_together(seats): occupied = seats.count("O") if occupied == 0 or occupied == len(seats): return 0, 0 empty_counts = [] current_available = 0 for seat in seats: if seat == "E": current_available += 1 else: if current_available > 0: empty_counts.append(current_available) current_available = 0 min_empty_seats = min(empty_counts) min_moves = min_empty_seats - 1 ways = empty_counts.count(min_empty_seats) return min_moves * occupied +1, ways N = int(input()) seats = input().strip() min_moves, ways = min_moves_together(seats) print(min_moves, ways)
Polygon with Maximum Area
Problem Description:
You are given N number of coordinates and you have to create a polygon from these points such that they will make a polygon with maximum area.
Note: coordinates provided in the input may or may not be in sequential form.
Constraints
1 <= N <= 10
Input:
First line contains an integer N which depicts number of co-ordinates
Next N lines consist of two space separated integer depicting coordinates of in form of xy
Output:
Print the maximum possible area possible by creating a polygon by joining the coordinates.
If the area is in decimal form, print the absolute value as output.
Time Limit (secs):
1
Examples:
Input:
4
0 0
2 0
0 2
2 2
Output:
4
Explanation:
As we can imagine that these points will make a square shape and the maximum possible area made by the polygon will be 4.
#include<bits/stdc++.h> using namespace std; struct Point { int x, y; }; // Comparator function to sort points based on x-coordinate (and y-coordinate in case of a tie) bool comparePoints(const Point &a, const Point &b) { return (a.x < b.x) || (a.x == b.x && a.y < b.y); } // Cross product of vectors (p1-p0) and (p2-p0) int crossProduct(const Point &p0, const Point &p1, const Point &p2) { int x1 = p1.x - p0.x; int y1 = p1.y - p0.y; int x2 = p2.x - p0.x; int y2 = p2.y - p0.y; return x1 * y2 - x2 * y1; } // Graham's Scan algorithm to find the convex hull vector convexHull(vector &points) { int n = points.size(); if (n <= 3) return points; // Sort the points based on x-coordinate (and y-coordinate in case of a tie) sort(points.begin(), points.end(), comparePoints); // Initialize the upper and lower hulls vector upperHull, lowerHull; // Build the upper hull for (int i = 0; i < n; i++) { while (upperHull.size() >= 2 && crossProduct(upperHull[upperHull.size() - 2], upperHull.back(), points[i]) <= 0) { upperHull.pop_back(); } upperHull.push_back(points[i]); } // Build the lower hull for (int i = n - 1; i >= 0; i--) { while (lowerHull.size() >= 2 && crossProduct(lowerHull[lowerHull.size() - 2], lowerHull.back(), points[i]) <= 0) { lowerHull.pop_back(); } lowerHull.push_back(points[i]); } // Combine the upper and lower hulls to get the convex hull upperHull.pop_back(); // Remove the last point to avoid duplication lowerHull.pop_back(); upperHull.insert(upperHull.end(), lowerHull.begin(), lowerHull.end()); return upperHull; } // Calculate the area of a polygon double calculateArea(vector &polygon) { int n = polygon.size(); if (n < 3) return 0.0; // Not a valid polygon double area = 0.0; for (int i = 0; i < n; i++) { int x1 = polygon[i].x; int y1 = polygon[i].y; int x2 = polygon[(i + 1) % n].x; int y2 = polygon[(i + 1) % n].y; area += (x1 * y2 - x2 * y1); } return abs(area) / 2.0; } int main() { int n; cin >> n; vector points(n); for (int i = 0; i < n; i++) { cin >> points[i].x >> points[i].y; } vector convexHullPoints = convexHull(points); double maxArea = calculateArea(convexHullPoints); cout << maxArea << endl; return 0; }
// ConvexHull.java import java.util.*; class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List points = new ArrayList<>(); for (int i = 0; i < n; i++) { int x = scanner.nextInt(); int y = scanner.nextInt(); points.add(new Point(x, y)); } List convexHullPoints = convexHull(points); long maxArea = calculateArea(convexHullPoints); // Use long to store the result as an integer System.out.println(maxArea); } // Comparator function to sort points based on x-coordinate (and y-coordinate in case of a tie) static class PointComparator implements Comparator { public int compare(Point a, Point b) { if (a.x < b.x || (a.x == b.x && a.y < b.y)) { return -1; } else if (a.x == b.x && a.y == b.y) { return 0; } else { return 1; } } } // Cross product of vectors (p1-p0) and (p2-p0) static int crossProduct(Point p0, Point p1, Point p2) { int x1 = p1.x - p0.x; int y1 = p1.y - p0.y; int x2 = p2.x - p0.x; int y2 = p2.y - p0.y; return x1 * y2 - x2 * y1; } // Graham's Scan algorithm to find the convex hull static List convexHull(List points) { int n = points.size(); if (n <= 3) return points; points.sort(new PointComparator()); List upperHull = new ArrayList<>(); List lowerHull = new ArrayList<>(); for (int i = 0; i < n; i++) { while (upperHull.size() >= 2 && crossProduct(upperHull.get(upperHull.size() - 2), upperHull.get(upperHull.size() - 1), points.get(i)) <= 0) { upperHull.remove(upperHull.size() - 1); } upperHull.add(points.get(i)); } for (int i = n - 1; i >= 0; i--) { while (lowerHull.size() >= 2 && crossProduct(lowerHull.get(lowerHull.size() - 2), lowerHull.get(lowerHull.size() - 1), points.get(i)) <= 0) { lowerHull.remove(lowerHull.size() - 1); } lowerHull.add(points.get(i)); } upperHull.remove(upperHull.size() - 1); lowerHull.remove(lowerHull.size() - 1); upperHull.addAll(lowerHull); return upperHull; } // Calculate the area of a polygon and return as an integer static long calculateArea(List polygon) { int n = polygon.size(); if (n < 3) return 0; // Not a valid polygon long area = 0; for (int i = 0; i < n; i++) { int x1 = polygon.get(i).x; int y1 = polygon.get(i).y; int x2 = polygon.get((i + 1) % n).x; int y2 = polygon.get((i + 1) % n).y; area += (x1 * (long)y2 - x2 * (long)y1); // Use long to avoid overflow } return Math.abs(area) / 2; } }
import math class Point: def __init__(self, x, y): self.x = x self.y = y def compare_points(a, b): if a.x < b.x or (a.x == b.x and a.y < b.y): return -1 elif a.x == b.x and a.y == b.y: return 0 else: return 1 def cross_product(p0, p1, p2): x1 = p1.x - p0.x y1 = p1.y - p0.y x2 = p2.x - p0.x y2 = p2.y - p0.y return x1 * y2 - x2 * y1 def convex_hull(points): n = len(points) if n <= 3: return points points.sort(key=lambda point: (point.x, point.y)) upper_hull = [] lower_hull = [] for i in range(n): while len(upper_hull) >= 2 and cross_product(upper_hull[-2], upper_hull[-1], points[i]) <= 0: upper_hull.pop() upper_hull.append(points[i]) for i in range(n - 1, -1, -1): while len(lower_hull) >= 2 and cross_product(lower_hull[-2], lower_hull[-1], points[i]) <= 0: lower_hull.pop() lower_hull.append(points[i]) upper_hull.pop() lower_hull.pop() upper_hull.extend(lower_hull) return upper_hull def calculate_area(polygon): n = len(polygon) if n < 3: return 0 area = 0 for i in range(n): x1 = polygon[i].x y1 = polygon[i].y x2 = polygon[(i + 1) % n].x y2 = polygon[(i + 1) % n].y area += (x1 * y2 - x2 * y1) return abs(area) // 2 if __name__ == "__main__": n = int(input()) points = [] for _ in range(n): x, y = map(int, input().split()) points.append(Point(x, y)) convex_hull_points = convex_hull(points) max_area = calculate_area(convex_hull_points) print(max_area)
Bank Compare Problem
Problem Description
Question – : There are two banks – Bank A and Bank B. Their interest rates vary. You have received offers from both banks in terms of the annual rate of interest, tenure, and variations of the rate of interest over the entire tenure.You have to choose the offer which costs you least interest and reject the other. Do the computation and make a wise choice.
The loan repayment happens at a monthly frequency and Equated Monthly Installment (EMI) is calculated using the formula given below :
EMI = loanAmount * monthlyInterestRate / ( 1 – 1 / (1 + monthlyInterestRate)^(numberOfYears * 12))
Constraints:
- 1 <= P <= 1000000
- 1 <=T <= 50
- 1<= N1 <= 30
- 1<= N2 <= 30
Input Format:
- First line: P principal (Loan Amount)
- Second line: T Total Tenure (in years).
- Third Line: N1 is the number of slabs of interest rates for a given period by Bank A. First slab starts from the first year and the second slab starts from the end of the first slab and so on.
- Next N1 line will contain the interest rate and their period.
- After N1 lines we will receive N2 viz. the number of slabs offered by the second bank.
- Next N2 lines are the number of slabs of interest rates for a given period by Bank B. The first slab starts from the first year and the second slab starts from the end of the first slab and so on.
- The period and rate will be delimited by single white space.
Output Format: Your decision either Bank A or Bank B.
Explanation:
- Example 1
- Input
- 10000
- 20
- 3
- 5 9.5
- 10 9.6
- 5 8.5
- 3
- 10 6.9
- 5 8.5
- 5 7.9
- Output: Bank B
- Example 2
- Input
- 500000
- 26
- 3
- 13 9.5
- 3 6.9
- 10 5.6
- 3
- 14 8.5
- 6 7.4
- 6 9.6
- Output: Bank A
#include<stdio.h> #include<math.h> int main() { double p,s,mi,sum,emi,bank[5],sq; int y,n,k,i,yrs,l=0; scanf(" %lf",&p); scanf(" %d",&y); for(k=0;k<2;k++) { scanf(" %d",&n); sum=0; for(i=0;i<n;i++) { scanf(" %d",&yrs); scanf(" %lf",&s); mi=0; sq=pow((1+s),yrs*12); emi= (p*(s))/(1-1/sq); sum= sum + emi; }bank[l++]=sum; } if(bank[0]<bank[1]) printf(" Bank A "); else printf(" Bank B "); return 0; }
Output 10000 20 3 5 9.5 10 9.6 5 8.5 3 10 6.9 5 8.5 5 7.9 Bank B
#include<bits/stdc++.h> using namespace std; int main() { double p,s,mi,sum,emi,bank[5],sq; int y,n,k,i,yrs,l=0; cin>>p; cin>>y; for(k=0;k<2;k++) { cin>>n; sum=0; for(i=0;i<n;i++) { cin>>yrs; cin>>s; mi=0; sq=pow((1+s),yrs*12); emi= (p*(s))/(1-1/sq); sum= sum + emi; } bank[l++]=sum; } if(bank[0]<bank[1]) cout<<("Bank A"); else cout<<("Bank B"); return 0; }
Output 10000 20 3 5 9.5 10 9.6 5 8.5 3 10 6.9 5 8.5 5 7.9 Bank B
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); double p,s,mi,sum,emi,sq; int y,n,k,yrs,l=0; double[] bank = new double[5]; System.out.println("Enter the principal amount"); p = sc.nextDouble(); System.out.println("Enter tenature year"); y = sc.nextInt(); for (k = 0; k < 2; k++) { System.out.println("Enter the no of slabs"); n = sc.nextInt(); sum=0; for (int i = 0; i < n; i++) { System.out.println("Enter the period :"); yrs = sc.nextInt(); System.out.println("Enter the interest :"); s = sc.nextDouble(); mi=0; sq=Math.pow((1+s), yrs*12); emi=(p*(s))/(1-1/sq); sum=sum+emi; } bank[l++]=sum; } if(bank[0]<bank[1]) System.out.println("Bank A"); else System.out.println("Bank B"); } }
Output 10000 20 3 5 9.5 10 9.6 5 8.5 3 10 6.9 5 8.5 5 7.9 Bank B
bank = [] principal = int(input()) year = int(input() for i in range(0, 2): # 2 Banks installments = int(input()) sum = 0 for i in range(0, installments): time, roi = [float(i) for i in input().split()] square = pow((1+roi), time*12) emi = (principal*(roi)/(1-1/square)) sum = sum + emi bank.append(sum) if bank[0] < bank[1]: print("Bank A") else: print("Bank B")
Output 10000 20 3 5 9.5 10 9.6 5 8.5 3 10 6.9 5 8.5 5 7.9 Bank B
Consecutive Prime Sum
Problem Description
Question – : Some prime numbers can be expressed as a sum of other consecutive prime numbers.
- For example
- 5 = 2 + 3,
- 17 = 2 + 3 + 5 + 7,
- 41 = 2 + 3 + 5 + 7 + 11 + 13.
Your task is to find out how many prime numbers which satisfy this property are present in the range 3 to N subject to a constraint that summation should always start with number 2.
Write code to find out the number of prime numbers that satisfy the above-mentioned property in a given range.
Input Format: First line contains a number N
Output Format: Print the total number of all such prime numbers which are less than or equal to N.
Constraints: 2<N<=12,000,000,000
#include<stdio.h> int prime(int b); int main() { int i,j,n,cnt,a[25],c,sum=0,count=0,k=0; printf("Enter a number : "); scanf("%d",&n); for(i=2;i<=n;i++) { cnt=1; for(j=2;j<=n/2;j++) { if(i%j==0) cnt=0; } if(cnt==1) { a[k]=i; k++; } } for(i=0;i<k;i++) { sum=sum+a[i]; c= prime(sum); if(c==1) count++; } printf(" %d",count); return 0; } int prime(int b) { int j,cnt; cnt=1; for(j=2;j<=b/2;j++) { if(b%j==0) cnt=0; } if(cnt==0) return 1; else return 0; }
Output Enter a number : 43 4
#include<bits/stdc++.h> using namespace std; int prime(int b) { int j,cnt; cnt=1; for(j=2;j<=b/2;j++) { if(b%j==0) cnt=0; } if(cnt==0) return 1; else return 0; } int main() { int i,j,n,cnt,a[25],c,sum=0,count=0,k=0; cout<<"Enter a number : "; cin>>n; for(i=2;i<=n;i++) { cnt=1; for(j=2;j<=n/2;j++) { if(i%j==0) cnt=0; } if(cnt==1) { a[k]=i; k++; } } for(i=0;i<k;i++) { sum=sum+a[i]; c= prime(sum); if(c==1) count++; } cout<<count; return 0; }
Output Enter a number : 5 1
import java.util.Scanner; class Main { static int prime(int b) { int j,cnt; cnt=1; for (j = 2; j <= b/2; j++) { if(b%j==0) cnt=0; } if(cnt==0) return 1; else return 0; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int i,j,n=0,cnt,c=0,sum=0,count=0,k=0; Main t = new Main(); int[] a = new int[25]; System.out.println("Enter no"); n = sc.nextInt(); for (i = 2; i <=n ; i++) { cnt=1; for (j = 2; j <= n/2; j++) { if(i%j==0) cnt=0; } if(cnt==1) { a[k]=i; k++; } } for (i = 0; i < k; i++) { sum=sum+a[i]; c=t.prime(sum); if(c==1) count++; } System.out.println(count); } }
Output 43 4
num = int(input()) arr = [] sum = 0 count = 0 if num > 1: for i in range(2, num + 2): for j in range(2, i): if i % j == 0: break else: arr.append(i) def is_prime(sum): for i in range(2, (sum // 2) +2): if sum % i == 0: return False else: return True for i in range(0, len(arr)): sum = sum + arr[i] if sum <= num: if is_prime(sum): count = count + 1 print(count)
Output 20 2
Counting Rock Sample
Problem Description
Question – : Juan Marquinho is a geologist and he needs to count rock samples in order to send it to a chemical laboratory. He has a problem: The laboratory only accepts rock samples by a range of its size in ppm (parts per million).
Juan Marquinho receives the rock samples one by one and he classifies the rock samples according to the range of the laboratory. This process is very hard because the number of rock samples may be in millions.
Juan Marquinho needs your help, your task is to develop a program to get the number of rocks in each of the ranges accepted by the laboratory.
Input Format: An positive integer S (the number of rock samples) separated by a blank space, and a positive integer R (the number of ranges of the laboratory); A list of the sizes of S samples (in ppm), as positive integers separated by space R lines where the ith line containing two positive integers, space separated, indicating the minimum size and maximum size respectively of the ith range.
Output Format: R lines where the ith line contains a single non-negative integer indicating the number of the samples which lie in the ith range.
Constraints:
- 10 <= S <= 10000
- 1 <= R <= 1000000
- 1<=size of Sample <= 1000
Example 1
- Input: 10 2
- 345 604 321 433 704 470 808 718 517 811
- 300 350
- 400 700
Output: 2 4
Explanation:
There are 10 samples (S) and 2 ranges ( R ). The samples are 345, 604,811. The ranges are 300-350 and 400-700. There are 2 samples in the first range (345 and 321) and 4 samples in the second range (604, 433, 470, 517). Hence the two lines of the output are 2 and 4
Example 2
- Input: 20 3
- 921 107 270 631 926 543 589 520 595 93 873 424 759 537 458 614 725 842 575 195
- 1 100
- 50 600
- 1 1000
Output: 1 12 20
Explanation:
There are 20 samples and 3 ranges. The samples are 921, 107 195. The ranges are 1-100, 50-600 and 1-1000. Note that the ranges are overlapping. The number of samples in each of the three ranges are 1, 12 and 20 respectively. Hence the three lines of the output are 1, 12 and 20.
#include<stdio.h> int main() { int a[1000],s,i,j,t,l1,l2,c=0; printf("Enter the number of elements : "); scanf("%d",&s); printf("Enter the number of ranges : "); scanf("%d",&t); printf("Enter the elements : "); for(i=0;i<s;i++) scanf("%d",&a[i]); printf("Enter the range : "); for(i=0;i<t;i++) { scanf("%d %d",&l1,&l2); for(j=0;j<s;j++) { if((a[j]>=l1)&&(a[j]<=l2)) c++; } printf("The desired output %d ",c); c=0; } return 0; }
Output 10 2 345 604 321 433 704 470 808 718 517 811 300 350 400 700 2 4
#include<bits/stdc++.h> using namespace std; int main() { int a[1000],s,i,j,t,l1,l2,c=0; cout<<("Enter the number of elements : "); cin>>s; cout<<("Enter the number of ranges : "); cin>>t; cout<<("Enter the elements : "); for(i=0;i<s;i++) cin>>a[i]; cout<<("Enter the range : "); for(i=0;i<t;i++) { cin>>l1>>l2; for(j=0;j<s;j++) { if((a[j]>=l1)&&(a[j]<=l2)) c++; } cout<<("The desired output %d ",c); c=0; } return 0; }
Output Enter the number of elements : 10 Enter the number of ranges : 2 Enter the elements : 345 604 321 433 704 470 808 718 517 811 Enter the ranges : 300 350 400 700 The desired Output : 2 4
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] a = new int[1000]; int s,i,j,t,l1=0,l2=0,c=0; System.out.println("Enter the no of sample"); s = sc.nextInt(); System.out.println("Enter the no of range"); t = sc.nextInt(); System.out.println("Enter the numbers"); for (i = 0; i < s; i++) { a[i] = sc.nextInt(); } for (i = 0; i< t; i++) { System.out.println("Enter the max and min range"); l1 = sc.nextInt(); l2 = sc.nextInt(); for (j = 0; j < s; j++) { if((a[j]>=l1)&&(a[j]<=l2)) c++; } System.out.println(c); c=0; } } }
samples, ranges =[int(i) for i in input().split()] count = 0 final = [] arr = list(map(int, input().split())) for i in range(0, ranges): range1, range2 = [int(i) for i in input().split()] for j in range(0, samples): if range1 <= arr[j] <= range2: count = count + 1 final.append(count) count = 0 for i in range(0, len(final)): print(final[i], end=" ")
Output 10 2 345 604 321 433 704 470 808 718 517 811 300 350 400 700 2 4
kth Largest factor of N
Problem Description
Question -: A positive integer d is said to be a factor of another positive integer N if when N is divided by d, the remainder obtained is zero. For example, for number 12, there are 6 factors 1, 2, 3, 4, 6, 12. Every positive integer k has at least two factors, 1 and the number k itself.Given two positive integers N and k, write a program to print the kth largest factor of N.
Input Format: The input is a comma-separated list of positive integer pairs (N, k).
Output Format: The kth highest factor of N. If N does not have k factors, the output should be 1.
Constraints:
- 1<N<10000000000
- 1<k<600.
You can assume that N will have no prime factors which are larger than 13.
Example 1
- Input: 12,3
- Output: 4
Explanation: N is 12, k is 3. The factors of 12 are (1,2,3,4,6,12). The highest factor is 12 and the third largest factor is 4. The output must be 4.
Example 2
- Input: 30,9
- Output: 1
Explanation: N is 30, k is 9. The factors of 30 are (1,2,3,5,6,10,15,30). There are only 8 factors. As k is more than the number of factors, the output is 1.
#include<stdio.h> void main() { int number,pos_of_factor,i,c=0; scanf("%d",&number); scanf("%d",&pos_of_factor); for(i=number;i>=1;i--) { if((number%i)==0) c++; if(c==pos_of_factor) { printf("%d",i); break; } } if(c<pos_of_factor) printf("1"); }
Output 12,3 4
#include<bits/stdc++.h> using namespace std; int main() { int number,pos_of_factor,i,c=0; cin>>number; cin>>pos_of_factor; for(i=number;i>=1;i--) { if((number%i)==0) c++; if(c==pos_of_factor) { cout<<i; break; } } if(c<pos_of_factor) cout<<1; return 0; }
Output 12,3 4
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int number,r,i,count=0; number = sc.nextInt(); r = sc.nextInt(); for (i = number; i >= 1; i--) { if((number%i)==0) count++; if(count==r) { System.out.println(i); break; } } if(count!=r) System.out.println(1); } }
Output 12,3 4
number, k = [int(i) for i in input().split(",")] factor = [] count = 0 for i in range(1, number+1): if number % i == 0: count = count + 1 factor.append(i) if count < k: print("1") else: print(factor[k])
Output 12,3 4
Collecting Candies
Problem Description
Question:- Krishna loves candies a lot, so whenever he gets them, he stores them so that he can eat them later whenever he wants to.
He has recently received N boxes of candies each containing Ci candies where Ci represents the total number of candies in the ith box. Krishna wants to store them in a single box. The only constraint is that he can choose any two boxes and store their joint contents in an empty box only. Assume that there are an infinite number of empty boxes available.
At a time he can pick up any two boxes for transferring and if both the boxes contain X and Y number of candies respectively, then it takes him exactly X+Y seconds of time. As he is too eager to collect all of them he has approached you to tell him the minimum time in which all the candies can be collected.
Input Format:
- The first line of input is the number of test case T
- Each test case is comprised of two inputs
- The first input of a test case is the number of boxes N
- The second input is N integers delimited by whitespace denoting the number of candies in each box
Output Format: Print minimum time required, in seconds, for each of the test cases. Print each output on a new line.
Constraints:
- 1 < T < 10
- 1 < N< 10000
- 1 < [Candies in each box] < 100009
S. No. | Input | Output |
---|---|---|
1 | 1 4 1 2 3 4 | 19 |
2 | 1 5 1 2 3 4 | 34 |
Explanation for sample input-output 1:
4 boxes, each containing 1, 2, 3 and 4 candies respectively.Adding 1 + 2 in a new box takes 3 seconds.Adding 3 + 3 in a new box takes 6 seconds.Adding 4 + 6 in a new box takes 10 seconds.Hence total time taken is 19 seconds. There could be other combinations also, but overall time does not go below 19 seconds.
Explanation for sample input-output 2:
5 boxes, each containing 1, 2, 3, 4 and 5 candies respectively.Adding 1 + 2 in a new box takes 3 seconds.Adding 3 + 3 in a new box takes 6 seconds.Adding 4 + 6 in a new box takes 10 seconds.Adding 5 + 10 in a new box takes 15 seconds.Hence total time taken is 34 seconds. There could be other combinations also, but overall time does not go below 33 seconds.
#include<stdio.h> int main() { int i,j; int num_box=0,k=0,sum=0,times=0,tst_case,temp=0; long c[10000],s[10000]; printf("Enter the number of test case:"); scanf("%d",&tst_case); printf("Enter the number of boxes:"); for(int l=0;l<tst_case;l++) { scanf("%d",&num_box); } printf("Enter the number of candies in each box:"); for(i=0;i<num_box;i++) { scanf("%ld",&c[i]); } for(i=0;i<num_box;i++) { for(j=i+1;j<num_box;j++) { if(c[i]>c[j]) { temp=c[i]; c[i]=c[j]; c[j]=temp; } } } sum=0; k=0; for(i=0;i<num_box;i++) { sum=sum+c[i]; s[k]=sum; k++; } times=0; printf("Minimum time requried:"); for(i=1;i<k;i++) times=times+s[i]; printf("%d\n",times); return 0; }
Output 1 4 1 2 3 4 19
#include<bits/stdc++.h> using namespace std; int main() { int i,j; int num_box=0,k=0,sum=0,times=0,tst_case,temp=0; long c[10000],s[10000]; cout<<("Enter the number of test case:"); cin>>tst_case; cout<<("Enter the number of boxes:"); for(int l=0;l<tst_case;l++) { cin>>num_box; } cout<<("Enter the number of candies in each box:"); for(i=0;i<num_box;i++) { cin>>c[i]; } for(i=0;i<num_box;i++) { for(j=i+1;j<num_box;j++) { if(c[i]>c[j]) { temp=c[i]; c[i]=c[j]; c[j]=temp; } } } sum=0; k=0; for(i=0;i<num_box;i++) { sum=sum+c[i]; s[k]=sum; k++; } times=0; cout<<("Minimum time requried:"); for(i=1;i<k;i++) times=times+s[i]; cout<<times; return 0; }
Output 1 4 1 2 3 4 19
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n, i, k = 0, sum = 0, s1 = 0, t, temp = 0, j; long c[] = new long[1000009]; long s[] = new long[100009]; System.out.println("Enter a no"); t = sc.nextInt(); for (int l = 0; l < t; l++) { n = sc.nextInt(); for (i = 0; i < n; i++) c[i] = sc.nextLong(); for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (c[i] > c[j]) { temp = (int) c[i]; c[i] = c[j]; c[j] = temp; } } } sum = 0; k = 0; for (i = 0; i < n; i++) { sum = (int) (sum + c[i]); s[k] = sum; k++; } s1 = 0; for (i = 1; i < k; i++) s1 = (int) (s1 + s[i]); System.out.println(s1); } } }
Output 1 4 1 2 3 4 19
T = int(input()) arr = [] arr1 = [] for i in range(0, T): N = int(input()) for i in range(0, N): arr.append(int(input())) arr.sort() count = arr[0] for i in range(1, len(arr)): count = count + arr[i] arr1.append(count) print(sum(arr1))
Output 1 4 1 2 3 4 19
Staircase Problem
Problem Description
There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time.
- Count the number of ways, the person can reach the top.
#include<stdio.h> int calc(int n); int count(int x); int main () { int n ; printf("Enter number of stairs : "); scanf("%d", &n); printf("Number of ways = %d", count(n)); getchar(); return 0; } int count(int x) { return calc(x + 1); } int calc(int n) { if (n <= 1) return n; return calc(n-1) + calc(n-2); }
Output Enter number of stairs : 5 Number of ways = 8
#include<bits/stdc++.h> using namespace std; int calc(int n); int count(int x); int main () { int n ; cout<<("Enter number of stairs : "); cin>>n; cout<<("Number of ways = %d", count(n)); return 0; } int count(int x) { return calc(x + 1); } int calc(int n) { if (n <= 1) return n; return calc(n-1) + calc(n-2); }
Output Enter number of stairs : 5 8
import java.util.Scanner; public class Main { static int path(int m , int n) { if(m==1 || n==1) return 1; return path(m-1,n)+path(m,n-1); } public static void main(String[] args) { System.out.println(path(4,4)); } }
Output 5 8
n = int(input("Enter number of Stairs:")) def calc(x): if x <= 1: return x return calc(x - 1) + calc(x - 2) def count(n): return calc(n + 1) print("Number of ways:", count(n))
Output 5 8
Maneuvering a Cave Problem
Problem Description
The task is to count all the possible paths from top left to bottom right of a m x n matrix with the constraints that from each cell you can either move only to right or down.
Input:
- First line consists of T test cases. First line of every test case consists of N and M, denoting the number of rows and number of columns respectively.
Output:
- Single line output i.e count of all the possible paths from top left to bottom right of a m x n matrix..
Constraints:
- 1<=T<=100
- 1<=N<=100
- 1<=M<=100
#include<stdio.h> int calc(int x, int y) ; int main() { int a,b; printf("Enter the number of rows of the matrix : "); scanf("%d",&a); printf("Enter the number of columns of the matrix : "); scanf("%d",&b); printf("%d", calc(a,b)); return 0; } int calc(int x, int y) { if (x == 1 || y == 1)// If there is a singular matrix { return 1; } else { return calc(x - 1, y) + calc(x, y - 1); } }
Output Enter the number of rows of the matrix : 3 Enter the number of columns of the matrix : 3 6
#include<bits/stdc++.h> using namespace std; int calc(int x, int y) ; int main() { int a,b,n; cout<<("Enter the number of test cases"); cin>>n; while(n!=0) { cout<<("Enter the number of rows of the matrix : "); cin>>a; cout<<("Enter the number of columns of the matrix : "); cin>>b; cout << "Number of ways - "<< calc(a,b)<<"\n"; n--; } return 0; } int calc(int x, int y) { if (x == 1 || y == 1)// If there is a singular matrix { return 1; } else { return calc(x - 1, y) + calc(x, y - 1); } }
Output Enter the number of test cases 2 Enter the number of rows of the matrix : 2 Enter the number of columns of the matrix : 2 Number of ways - 2 Enter the number of rowa of the matrix : 3 Enter the number of columns of the matrix : 3 Number of ways - 6
import java.util.Scanner; public class Main { static int path(int m , int n) { if(m==1 || n==1) return 1; return path(m-1,n)+path(m,n-1); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a,b,c; System.out.println("Enter test cases : "); c=sc.nextInt(); while(c-- > 0) { System.out.println("Enter number of rows and columns : "); a=sc.nextInt(); b=sc.nextInt(); System.out.println(path(a,b)); } } }
Output Enter number of test cases : 2 Enter number of rows and columns : 3 3 6 Enter number of rows and columns : 4 2 4
a = int(input()) b = int(input()) def calculate(a, b): if a == 1 or b == 1: return 1 else: return calculate(a - 1, b) + calculate(a, b - 1) print(calculate(a, b))
Output 3 3 6
Houses Problem
Problem Description
Question:- There are n houses build in a line, each of which contains some value in it.
A thief is going to steal the maximal value of these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two neighbours left and right side.
What is the maximum stolen value?
Sample Input: val[] = {6, 7, 1, 3, 8, 2, 5}
Sample Output: 20
#include<bits/stdc++.h> using namespace std; int maxLoot(int *hval, int n) ; int main() { int hval[]= {6, 7, 1, 3, 8, 2, 4, 12}; int n = sizeof(hval)/sizeof(hval[0]); cout << "Maximum loot possible : " << maxLoot(hval, n); return 0; } // calculate the maximum stolen value int maxLoot(int *hval, int n) { if (n == 0) return 0; if (n == 1) return hval[0]; if (n == 2) return max(hval[0], hval[1]); // dp[i] represent the maximum value stolen // so far after reaching house i. int dp[n]; // Initialize the dp[0] and dp[1] dp[0] = hval[0]; dp[1] = max(hval[0], hval[1]); // Fill remaining positions for (int i = 2; i<n; i++) dp[i] = max(hval[i]+dp[i-2], dp[i-1]); return dp[n-1]; }
Output
6 7 1 3 8 2 5
20
import java.util.Scanner; public class Main { static int prep(int hval[],int n) { if(n==0) return 0; if(n==1) return hval[0]; if(n==2) return Math.max(hval[0],hval[1]); int[] dp = new int[n]; dp[0]=hval[0]; dp[1]=Math.max(hval[0],hval[1]); for (int i = 2; i < n; i++) { dp[i]=Math.max(hval[i]+dp[i-2],dp[i-1]); } return dp[n-1]; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int hval[] = {3,2,4,6,7,1}; int n=hval.length; System.out.println("Max loot value :"+prep(hval,n)); } }
Output
6 7 1 3 8 2 5
20
num = list(map(int, input().split())) sum = num[0] for i in range(0, len(num)//2): sum = sum + int(num[i]) print(sum)
Output
6 7 1 3 8 2 5
20
Square Free Numbers Problem
Problem Description
In the theory of numbers, square free numbers have a special place. A square free number is one that is not divisible by a perfect square (other than 1). Thus 72 is divisible by 36 (a perfect square), and is not a square free number, but 70 has factors 1, 2, 5, 7, 10, 14, 35 and 70. As none of these are perfect squares (other than 1), 70 is a square free number.
For some algorithms, it is important to find out the square free numbers that divide a number. Note that 1 is not considered a square free number.
In this problem, you are asked to write a program to find the number of square free numbers that divide a given number.
Input:-
- The only line of the input is a single integer N which is divisible by no prime number larger than 19.
Output:-
- One line containing an integer that gives the number of square free numbers (not including 1).
Constraints:-
- N < 10^9
Complexity:-
- Simple
Time Limit:-
- 1
Examples
Example 1
- Input:-
20 - Output:-
3
Explanation
N=20
If we list the numbers that divide 20, they are
1, 2, 4, 5, 10, 20
1 is not a square free number, 4 is a perfect square, and 20 is divisible by 4, a perfect square. 2 and 5, being prime, are square free, and 10 is divisible by 1,2,5 and 10, none of which are perfect squares. Hence the square free numbers that divide 20 are 2, 5, 10. Hence the result is 3.
Example 2
- Input:-
72 - Output:-
3
Explanation
N=72. The numbers that divide 72 are
1, 2, 3, 4, 6, 8, 9, 12, 18, 24, 36, 72
1 is not considered square free. 4, 9 and 36 are perfect squares, and 8,12,18,24 and 72 are divisible by one of the. Hence only 2, 3 and 6 are square free. (It is easily seen that none of them are divisible by a perfect square). The result is 3.
#include<stdio.h> #include<math.h> int main() { long int n; double sqnum; long int i,j=0,flag,chksqr,temp[10000]; int count=0,k; printf("Enter the number:"); scanf("%ld",&n); for(i=2;i<=n/2;i++) { if(n%i==0) { count++; sqnum=sqrt(i); chksqr=sqnum; if(chksqr==sqnum) { count--; temp[j]=i; j++; } else { for(k=0;k<j;k++) { if(i>temp[k] && j!=0) { if(i%temp[k]==0) { count--; k=j+1; } } else break; } } } } printf("%d",count); return 0; }
Output Enter the number : 20 3
#include<bits/stdc++.h> using namespace std; int main() { long int n; double sqnum; long int i,j=0,flag,chksqr,temp[10000]; int count=0,k; cout<<"Enter the number:"; cin>>n; for(i=2;i<=n/2;i++) { if(n%i==0) { count++; sqnum=sqrt(i); chksqr=sqnum; if(chksqr==sqnum) { count--; temp[j]=i; j++; } else { for(k=0;k<j;k++) { if(i>temp[k] && j!=0) { if(i%temp[k]==0) { count--; k=j+1; } } else break; } } } } cout<<count; return 0; }
Output Enter the number : 20 3
Coin Distribution Problem
Problem Statement
Find the minimum number of coins required to form any value between 1 to N,both inclusive.Cumulative value of coins should not exceed N. Coin denominations are 1 Rupee, 2 Rupee and 5 Rupee.Let’s Understand the problem using the following example. Consider the value of N is 13, then the minimum number of coins required to formulate any value between 1 and 13, is 6. One 5 Rupee, three 2 Rupee and two 1 Rupee coins are required to realize any value between 1 and 13. Hence this is the answer.However, if one takes two 5 Rupee coins, one 2 rupee coin and two 1 rupee coin, then too all values between 1 and 13 are achieved. But since the cumulative value of all coins equals 14, i.e., exceeds 13, this is not the answer.
- Input Format:
- A single integer value.
- Output Format:
- Four space separated integer values.
- 1st – Total number of coins.
- 2nd – number of 5 Rupee coins.
- 3rd – number of 2 Rupee coins.
- 4th – number of 1 Rupee coins.
- Four space separated integer values.
- Constraints:
- 0 < n < 1000
Refer the sample output for formatting
Sample Input
13
Sample Output
6 1 3 2
Explanation
- The minimum number of coins required is 6 with in it:
- minimum number of 5 Rupee coins = 1
- minimum number of 2 Rupee coins = 3
- minimum number of 1 Rupee coins = 2
Using these coins, we can form any value with in the given value and itself, like below:
Here the given value is 13
- For 1 = one 1 Rupee coin
- For 2 = one 2 Rupee coin
- For 3 = one 1 Rupee coin and one 2 Rupee coins
- For 4 = two 2 Rupee coins
- For 5 = one 5 Rupee coin
- For 6 = one 5 Rupee and one 1 Rupee coins
- For 7 = one 5 Rupee and one 2 Rupee coins
- For 8 = one 5 Rupee, one 2 Rupee and one 1 Rupee coins
- For 9 = one 5 Rupee and two 2 Rupee coins
- For 10 = one 5 Rupee, two 2 Rupee and one 1 Rupee coins
- For 11 = one 5 Rupee, two 2 Rupee and two 1 Rupee coins
- For 12 = one 5 Rupee, three 2 Rupee and one 1 Rupee coins
- For 13 = one 5 Rupee, three 2 Rupee and two 1 Rupee coins
number = int (input ()) five = int ((number - 4) / 5) if ((number - 5 * five) % 2)== 0: one = 2 else: one = 1 two = (number - 5 * five - one) //2 print (one + two + five, five, two, one)
import java.util.*; public class Main { public static void main (String[]args) { System.out.println ("Enter the Number"); Scanner s = new Scanner (System.in); int number = s.nextInt (); int one = 0, two = 0; int five = (number - 4) / 5; if (((number - 5 * five) % 2) == 0) { one = 2; } else { one = 1; } two = (number - 5 * five - one) / 2; System.out.println (one + two + five); System.out.println (five); System.out.println (two); System.out.println (one); } }
Total Distance Covered by the Beetle
Problem Description
A 10cm x 10cm x 10cm solid cube rests on the ground. It has a beetle on it, as well as some sweet honey spots on the cube’s surface. The beetle begins at a point on the cube’s surface and moves in a clockwise direction along the cube’s surface to the honey spots.
- If it goes from one point on the same face to another (say, X to Y), it goes in an arc of a circle that subtends an angle of 60 degrees at the circle’s center.
- If it travels from one point to another on a different face, it takes the shortest path on the cube’s surface, except that it never travels along its bottom.
The beetle is a Cartesian geometry student who knows the coordinates (x, y, z) of all the points it needs to visit. Its coordinate origin is one of the cube’s corners on the ground, and the z-axis points up. As a result, z=0 is the bottom surface (on which it does not crawl), and z=10 is the top. The beetle keeps track of all distances traveled and rounded the distance to two decimal places when it arrives at the following location so that the final distance is a sum of the rounded distances from spot to spot.
Input
The first line returns an integer N, the total number of points visited by the beetle (including the starting point).
The second line contains 3N non-negative numbers, each with two decimal places. These are to be interpreted as the x, y, and z coordinates of the points the beetle must visit in the given order.
Output
One line containing a number representing the total distance traveled by the beetle to two decimal places. Even if the travel distance is an integer, the output should have two decimal places.
Constraints
None of the points visited by the beetle are on the bottom face (z=0) or on any of the cube’s edges (the lines where two faces meet)
2<=N<=10
Example
Input : 31 1 10 2 1 10 0 1 9
Output : 4.05
Explanation :The beetle visits three different locations (N=3). The beetle begins on the cube's top face (z=10) at point (1,1,10) and moves to another point on the same face (2,1,10). Although the straight line distance is one, it travels on the arc of a circle with an angle of 60 degrees at its center and thus travels (2*pi)/6 or 1.05 (note that it rounds the distance at each leg of the journey). It moves along the cube's surface from (2,1,10) on the face z=10 to (0,1,9) on the face x=0. This is a three-mile distance. The total travel distance is 1.05+3=4.05. The result is 4.05
#include<stdio.h> #include<math.h> #include<stdlib.h> #define PIE 3.14 int s_x,s_y,s_z; float shortDist(int x, int y, int z) { float dis; // check if the Z-axis and any other one axis are the same. if(z == s_z && ( y == s_y || x == s_x) && s_z != 0) { //check if the x axis of next co-ordinate is same if(x != s_x) dis = (2 * PIE * (abs(x-s_x)))/6.0; //check if the y axis of next co-ordinate is same else dis = (2 * PIE * (abs(y-s_y)))/6.0; } // finddistance between x and y and the abs distance of Z axis else dis = (int)(sqrt(pow(x-s_x,2) + pow(y-s_y,2)) + abs(z-s_z)); s_x = x; s_y = y; s_z = z; return dis; } int main() { int n; scanf("%d", &n); n = 3 * n; int arr[n]; for(int i = 0;i < n;i++) scanf("%d", &arr[i]); float sum = 0.0; s_x = arr[0]; s_y = arr[1]; s_z = arr[2]; for(int i=3;i<n;i+=3) { sum += shortDist(arr[i],arr[i+1],arr[i+2]); } printf("%.2f",sum); }
#include<bits/stdc++.h> using namespace std; #define PIE 3.14 int s_x,s_y,s_z; float shortDist(int x, int y, int z) { float dis; // check if the Z-axis and any other one axis are the same. if(z == s_z && ( y == s_y || x == s_x) && s_z != 0) { //check if the x axis of next co-ordinate is same if(x != s_x) dis = (2 * PIE * (abs(x-s_x)))/6.0; //check if the y axis of next co-ordinate is same else dis = (2 * PIE * (abs(y-s_y)))/6.0; } // finddistance between x and y and the abs distance of Z axis else dis = (int)(sqrt(pow(x-s_x,2) + pow(y-s_y,2)) + abs(z-s_z)); s_x = x; s_y = y; s_z = z; return dis; } int main() { int n; cin>>n; n = 3 * n; int arr[n]; for(int i = 0;i < n;i++) cin>>arr[i]; float sum = 0.0; s_x = arr[0]; s_y = arr[1]; s_z = arr[2]; for(int i=3;i<n;i+=3) { sum += shortDist(arr[i],arr[i+1],arr[i+2]); } printf("%.2f",sum); }
import java.util.*; import java.lang.*; import java.io.*; class Main{ final static float PIE = 3.14f; static int s_x, s_y, s_z; public static void main(String[] args) { int i, N, x, y, z; int arr[] = new int[50]; float sum = 0.0f; Scanner sc = new Scanner(System.in); N = sc.nextInt(); N = 3 * N; for(i = 0; i < N; i++){ arr[i] = sc.nextInt(); } s_x = arr[0]; s_y = arr[1]; s_z = arr[2]; for(i = 3; i < N ; i += 3){ sum += shortDist(arr[i], arr[i+1], arr[i+2]); } System.out.printf("%.2f", sum); } private static float shortDist(int x, int y, int z) { float dis; // check if the Z-axis and any other one axis are the same. if(z == s_z && (y == s_y || x == s_x ) && s_z != 0){ //check if the x axis of next co-ordinate is same if(x != s_x){ dis = (2 * PIE * (Math.abs(x - s_x))) / 6.0f; } //check if the y axis of next co-ordinate is same else{ dis = (2 * PIE * (Math.abs(y - s_y))) / 6.0f; } } else{ dis = (int)(Math.sqrt(Math.pow(x - s_x, 2) + Math.pow(y - s_y, 2)) + Math.abs(z - s_z)); } s_x = x; s_y = y; s_z = z; return dis; } }
import math PIE=3.14 def shortDist( x,y,z,sx,sy,sz): dis = 0.0 # if the x or y axis same as z axis if(z == s_z and (y == s_y or x==s_x) and s_z != 0): # if the x axis of next co-ordinate is same if(x != s_x): dis = (2 * PIE * (abs(x - s_x)))/6.0 # if the y axis of next co-ordinate is same else: dis = (2 * PIE * (abs(y -s_y)))/6.0 # else means bee is going to another face #finding eculidean distance else: dis = int((math.sqrt(pow(x-s_x, 2) + pow(y-s_y, 2)) + abs(z - s_z))) s_x = x s_y = y s_z = z return dist,s_x,s_y,s_z n=int(input()) arr = [int(x) for x in input().split()] s_x = arr[0] s_y = arr[1] s_z = arr[2] ans=0 for j in range(3,3*n,3): x,s_x,s_y,s_z= shortDist(arr[j],arr[j+1],arr[j+2],s_x,s_y,s_z) ans += x print(round(ans,2))
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment