Magicpin Coding Questions and Answers
Magicpin Coding Questions with Solutions
Here, Magicpin Coding Questions and Answers page will help you to get all the sample coding questions with solutions that are included in Online Assessment and Technical Interview of Magicpin for hiring Software Development Intern and Analyst Intern.
In the end of Magicpin Coding Questions and Answers page you will get FAQ’s related hiring process of Magicpin for hiring freshers.
Magicpin Coding Questions with Answers
Question 1: Share Holder (R -> Hard)
Problem statement :
Ratan is a crazy rich person. And he is blessed with luck, so he always made the best profit possible with the shares he bought. That means he bought a share at a low price and sold it at a high price to maximize his profit. Now you are an income tax officer and you need to calculate the profit he made with the given values of stock prices each day. You have to calculate only the maximum profit Ratan earned.
Note that:
Ratan never goes into loss.
Example 1 :
Price=[1,6,2]
Ratan buys it on the first day and sells it on the second.
Example 2 :
Price=[9,8,6]
The Price always went down, Ratan never bought it.
Input Format:
First line with an integer n, denoting the number days with the value of the stack
Next n days, telling the price of the stock on that very day.
Output Format:
Maximum profit done by Ratan in a single line.
Constraints:
Number of days <=10^8
Sample Input for Custom Testing
STDIN
———–
7
1
9
2
11
1
9
2
Sample Output
10
Explanation
The maximum profit possible is when Ratan buys it in 1 rupees and sells it in 11.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
#include <bits/stdc++.h> using namespace std; int solve(vector < int > v) { int n = v.size(); if (n == 0) return 0; int mx = v[0]; for (int i = 1; i < n; i++) mx = max(mx, v[i]); if (mx <= 0) return 0; int mxSum = 0; int cSum = 0; for (int i = 0; i < n; i++) { cSum += v[i]; if (cSum < 0) cSum = 0; mxSum = max(mxSum, cSum); } return mxSum; } int main() { int n; cin >> n; int price[n]; for (int i = 0; i < n; i++) cin >> price[i]; vector < int > diff; for (int i = n - 2; i >= 0; i--) diff.push_back(price[i + 1] - price[i]); int ans = solve(diff); if (ans < 0) cout << 0 << endl; else cout << ans << endl; }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int price[] = new int[n]; for (int i = 0; i < n; i++) { price[i] = sc.nextInt(); } Vector < Integer > diff = new Vector < > (); for (int i = n - 2; i >= 0; i--) { diff.add(price[i + 1] - price[i]); } int ans = solve(diff); if (ans < 0) { System.out.println(0); } else { System.out.println(ans); } } private static int solve(Vector < Integer > v) { int n = v.size(); if (n == 0) { return 0; } int mx = v.get(0); for (int i = 1; i < n; i++) { mx = Math.max(mx, v.get(i)); } if (mx <= 0) { return 0; } int mxSum = 0, csum = 0; for (int i = 0; i < n; i++) { csum += v.get(i); if (csum < 0) csum = 0; mxSum = Math.max(csum, mxSum); } return mxSum; } }
def func(diff): n=len(diff) if n==0: return 0 mx=max(diff) if mx <= 0: return 0 mxS=0 cS=0 for i in diff: cS+=i if cS <= 0: cS=0 mxS=max(cS,mxS) return mxS n=int(input()) arr=[] diff=[] ans=[0] for i in range(n): arr.append(int(input())) for i in range(n-1): diff.append(arr[i+1]-arr[i]) ans=func(diff) if ans < 0: print("0") else: print(ans)
Question 02 : Device Name System
Problem statement: Rocky is a software engineer and he is creating his own operating system called “myFirst os”. myFirst os is a GUI (Graphical user interface) based operating system where everything is stored in files and folders. He is facing issues on creating unique folder names for the operating system . Help rocky to create the unique folder name for it’s os.If folder name already exists in the system and integer number is added at the name to make it unique. The integer added starts with 1 and is incremented by 1 for each new request of an existing folder name. Given a list of folder names , process all requests and return an array of corresponding folder names.
Example
- n=5
- foldername= [‘home’ , ‘myfirst’ ,’downloads’, ‘myfirst’, ‘myfirst’]
- Foldername[0] = ‘home’ is unique.
- Foldername[1] = ‘myfirst’ is unique.
- foldername [2] =’downloads’ is unique.
- Foldername[3] =’myfirst’ already exists in our system. So Add1 at the end of the folder name i.e foldername[3] =”myfirst1″
- Foldername[4 ]=’myfirst’ also already exists in our system.So add 2 at the end of the folder name i.e. foldername[4]=”myfirst2″.
Function description
- Complete the function folderNameSystem In the editor below
- folderNameSystem has the following parameters
- string foldername[n]: an array of folder name string in the order requested
Returns:
- String[n]: an array of strings usernames in the order assigned
Constraints
- 1<=n<=10^4
- 1<=length of foldername[i]<20
- foldername[i] contains only lowercase english letter in the range ascii[a-z]
Input Format:
- The first line contains an integer n , denoting the size of the array usernames Each line i of the n subsequent lines (where i<=0<=n) contains a string usernames[i] representing a username request in the order received.
Sample case 0
- 4
- home
- download
- first
- first
Sample Output 0
- home
- download
- first
- first1
Explanation 0
- foldername[0] = ‘home’ is unique
- foldername[1]=’download’ is unique
- foldername[2]= ‘first’ is unique
- foldername[3]=’first’ is already existing . so add 1 to it and it become first1
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; vector v(n); for(int i=0;i<n;i++) cin>>v[i]; map<string,int> m; for(auto i:v){ if(m[i]) cout<<i<<m[i]<<endl; else cout<<i<<endl; m[i]++; } }
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); LinkedHashMap<String, Integer> map=new LinkedHashMap<>(); for(int i=0;i<n;i++){ String str=sc.next(); if(map.containsKey(str)){ int count=map.get(str); count = count+1; map.put(str,count); } else map.put(str,1); } Set s = map.entrySet(); Iterator itr = s.iterator(); while(itr.hasNext()){ Map.Entry m=(Map.Entry)itr.next(); int value=(Integer)m.getValue(); System.out.println(m.getKey()); value--; for(int i=1;i<=value;i++){ System.out.println(m.getKey()+""+i); value--; } } } }
n=int(input()) arr = [] ans = "" for i in range(n): arr.append(input()) print() for i in range(n): if arr[:i+1].count(arr[i])>1: ans = arr[i]+str(arr[:i+1].count(arr[i])-1) else: ans = arr[i] print(ans)
Question 3 : Stars Between Bars
Problem statement :
Given a string s consisting of stars “*” and bars “|” ,an array of starting indices starIndex,and an array of ending indices endIndex,determine the number of stars between any two bars within the substrings between the two indices inclusive . NOTE that in this problem indexing starts at 1.
- A Star is represented as an asterisk [*=ascii decimal 42]
- A Bar is represented as a Pipe [“|”=ascii decimal 124]
Example :
s=’|**|*|’
startIndex=[1,1]
endIndex=[5,6]
For the first pair of indices (1,5) the substrings is “|**|*” . There are 2 stars between a pair of bars
For the second pair of indices (1,6) the substring is “|**|*|” and there are 2+1=3 stars in between the bars.
Both of the answers are returned to the array [2,3].
Constraints :
int [n];each element[i] answers the query of startIndex[i] to endindex[i]
Constraints
1<=n<=105
1<=StartInde[i]<=endIndex[i]
Each Character of s is either “*” or “|”
>Input Format for Custom testing
First line contains a string S the next line contains an integer n , the no.of elements in startIndex. Each line i of the n subsequent lines contains an integer of startIndex.the next line contains an integer n , the no.of elements in endIndex. Each line i of the n subsequent lines contains an integer of endindex
>Sample Case 0
Sample Input for Custom Testing
*|*| → s=”*|*|”
1 → startindex[] size=1
1 → startindex= 1
1 → endindex[] size=1
3 → endindex=3
Sample output :
0
Explanation :
The substring from index =1 to index=3 is “*|*” . there is no consecutive pair of bars in this string.
#include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; int n; cin >> n; int st[n], ed[n]; for (int i = 0; i < n; i++) { cin >> st[i]; st[i]--; } cin >> n; for (int i = 0; i < n; i++) { cin >> ed[i]; ed[i]--; } vector < int > bars; for (int i = 0; i < s.length(); i++) { if (s[i] == '|') bars.push_back(i); } for (int i = 0; i < n; i++) { int idx = lower_bound(bars.begin(), bars.end(), st[i]) - bars.begin(); st[i] = bars[idx]; idx = lower_bound(bars.begin(), bars.end(), ed[i]) - bars.begin(); if (idx == 0 || bars[idx] == ed[i]) continue; ed[i] = bars[idx - 1]; } int sz = s.length(); int starCt[sz] = { 0 }; if (s[0] == '*') starCt[0] = 1; for (int i = 1; i < sz; i++) { starCt[i] = starCt[i - 1] + (s[i] == '*'); } for (int i = 0; i < n; i++) { if (st[i] >= ed[i]) { cout << 0 << endl; } else { int ans = starCt[ed[i]]; if (st[i] > 0) ans -= starCt[st[i] - 1]; cout << ans << endl; } } return 0; }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); int n = sc.nextInt(); int startIndex[] = new int[n]; int endIndex[] = new int[n]; for (int i = 0; i < n; i++) startIndex[i] = sc.nextInt(); for (int i = 0; i < n; i++) endIndex[i] = sc.nextInt(); int count = 0; for (int i = 0; i < n; i++) { count = 0; String sub = str.substring(startIndex[i] - 1, endIndex[i]); int start = sub.indexOf("|"); int end = sub.lastIndexOf("|"); for (int j = start; j < end; j++) if (sub.charAt(j) == '*') count++; System.out.print(count + " "); }
s = input() start = [] end = [] n = int(input()) for i in range(n): start.append(int(input())) for i in range(int(input())): end.append(int(input())) for i in range(n): Str = s[start[i] - 1 : end[i]] print(Str.strip("*").count("*"))
Question 4 :Vampire Battle (R->Medium)
Problem statement :
Stephan is a vampire. And he is fighting with his brother Damon. Vampires get energy from human bloods, so they need to feed on human blood, killing the human beings. Stephan is also less inhuman, so he will like to take less life in his hand. Now all the people’s blood has some power, which increases the powers of the Vampire. Stephan just needs to be more powerful than Damon, killing the least human possible. Tell the total power Steohan will have after drinking the bloods before the battle.
Note that: Damon is a beast, so no human being will be left after Damon drinks everyone’s blood. But Stephan always comes early in the town.
Input Format :
First line with the number of people in the town, n.
Second line with a string with n characters, denoting the one digit power in every blood.
Output Format :
Total minimum power Stephan will gather before the battle.
Constraints :
n<=10^4
Sample input :
6
093212
Sample output:
9
Explanation :
Stephan riches the town, drinks the blood with power 9. Now Damon cannot reach 9 by drinking all the other bloods.
#include <bits/stdc++.h> using namespace std; int main() { int n, sum = 0, sum1 = 0; cin >> n; string s; cin >> s; sort(s.begin(), s.end(), greater < char > ()); for (auto i: s) sum += (i - '0'); for (auto i: s) { if (sum1 > sum) break; sum1 += (i - '0'); sum -= i - '0'; } cout << sum1; }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String str = sc.next(); char arr[] = str.toCharArray(); int a[] = new int[arr.length]; for (int i = 0; i < a.length; i++) a[i] = Integer.parseInt(arr[i] + ""); Arrays.sort(a); int sum = 0; for (int i = 0; i < a.length; i++) sum = sum + a[i]; int sumA = 0; int sumB = sum; ArrayList < Integer > subsetA = new ArrayList < Integer > (); for (int i = a.length - 1; i >= 0; i--) { sumA = sumA + a[i]; sumB = sumB - a[i]; subsetA.add(a[i]); if (sumA > sumB) break; } Iterator itr = subsetA.iterator(); while (itr.hasNext()) { System.out.print((Integer) itr.next()); } } }
n = int(input()) ar = input() sorted(ar, reverse=True) br = [] s = 0 aa = [] for i in ar: aa.append(int(i)) su = sum(aa) while s <= su: s += aa[0] su = su - (aa[0]) br.append(aa.pop(0)) print(sum(br))
Question 5 : Last student’s ID
There is an id code that is supposed to be given to all the aspirants of an exam. It is actually a substring of a given string. That means, the authority takes a string and then assigns all the unique substrings to all the students. Suppose there is a string “abcde”, so the ids of the students will be “a”, “ab”, ”abc”, ”abcd”, ”abcde”, ”b”, ”bc”, ”bcd”, ”bcde”, ”c”, ”cd”, ”cde”, ”d”, ”de”, ”e”.
The students are standing in a line according to the lexicographic order of their given ids. You have to find out the id of the last student for the given input string from which the ids are generated and then arranged in lexicographic order.
Input Format:
- Single line with the id generating string
Output format:
- The last id as per lexicographical order.
Constraints:
- Number of characters in the string<=10^9
Sample Input:
abdc
Sample output:
dc
Explanation:
The last student as per lexicographical order will be with the id dc. The lexicographical order for adbc will be :
a
ab
abd
abdc
b
bd
bdc
c
d
dc
#include<bits/stdc++.h> using namespace std; int main() { string s; cin>>s; char c = s[0]; int j = 0; for(int i=1;i<s.length();i++) if(c<s[i]) {j=i;c=s[i];} cout<<s.substr(j,s.length()-j); }
import java.util.*; public class Main { public static String maxString(char set[]) { int n=set.length; String temp=""; TreeSet list=new TreeSet<>(); for(int i=0;i<n;i++) { temp=""; for(int j=i;j<n;j++) { temp=temp+set[j]; list.add(temp); } } return list.last(); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); String str=sc.next(); char arr[]=str.toCharArray(); System.out.println(maxString(arr)); } }
s=input() j=1 c=0 while j<len(s): if ord(s[c])<ord(s[j]): c=j j+=1 print(s[c:])
Question 6 : Elements of Matrix
Problem Statement
You are required to input the size of the matrix then the elements of matrix, then you have to divide the main matrix in two sub matrices (even and odd) in such a way that element at 0 index will be considered as even and element at 1st index will be considered as odd and so on. then you have sort the even and odd matrices in ascending order then print the sum of second largest number from both the matrices
Example
- enter the size of array : 5
- enter element at 0 index : 3
- enter element at 1 index : 4
- enter element at 2 index : 1
- enter element at 3 index : 7
- enter element at 4 index : 9
Sorted even array : 1 3 9
Sorted odd array : 4 7
7
#include<stdio.h> int main() { int arr[100]; int length, i, j, oddlen, evenlen, temp; int odd[50], even[50]; printf("Enter the length of the array: "); scanf("%d", &length); for (i = 0; i < length; i++) { printf("Enter element at index %d: ", i); scanf("%d", &arr[i]); } if (length % 2 == 0) { oddlen = length / 2; evenlen = length / 2; } else { oddlen = length / 2; evenlen = (length / 2) + 1; } for (i = 0; i < length; i++) { if (i % 2 == 0) { even[i / 2] = arr[i]; } else { odd[i / 2] = arr[i]; } } for (i = 0; i < evenlen - 1; i++) { for (j = i + 1; j < evenlen; j++) { if (even[i] > even[j]) { temp = even[i]; even[i] = even[j]; even[j] = temp; } } } for (i = 0; i < oddlen - 1; i++) { for (j = i + 1; j < oddlen; j++) { if (odd[i] > odd[j]) { temp = odd[i]; odd[i] = odd[j]; odd[j] = temp; } } } printf("\nSorted even array: "); for (i = 0; i < evenlen; i++) { printf("%d ", even[i]); } printf("\n"); printf("Sorted odd array: "); for (i = 0; i < oddlen; i++) { printf("%d ", odd[i]); } printf("\n"); printf("%d", even[evenlen - 2] + odd[oddlen - 2]); return 0; }
#include<bits/stdc++.h> using namespace std; int main () { int arr[100]; int length, i, j, oddlen, evenlen, temp, c, d; int odd[50], even[50]; cout << "enter the length of array : "; cin >> length; for (i = 0; i < length; i++) { cout << "Enter element at " << i << " index : "; cin >> arr[i]; } if (length % 2 == 0) { oddlen = length / 2; evenlen = length / 2; } else { oddlen = length / 2; evenlen = (length / 2) + 1; } for (i = 0; i < length; i++) // seperation of even and odd array { if (i % 2 == 0) { even[i / 2] = arr[i]; } else { odd[i / 2] = arr[i]; } } for (i = 0; i < evenlen - 1; i++) // sorting of even array { for (j = i + 1; j < evenlen; j++) { temp = 0; if (even[i] > even[j]) { temp = even[i]; even[i] = even[j]; even[j] = temp; } } } for (i = 0; i < oddlen - 1; i++) // sorting of odd array { for (j = i + 1; j < oddlen; j++) { temp = 0; if (odd[i] > odd[j]) { temp = odd[i]; odd[i] = odd[j]; odd[j] = temp; } } } cout << "\nSorted even array : "; // printing even array for (i = 0; i < evenlen; i++) { cout << even[i] << " "; } cout << "\n"; cout << "Sorted odd array : "; // printing odd array for (i = 0; i < oddlen; i++) { cout << odd[i] << " "; } cout << endl; cout << even[evenlen - 2] + odd[oddlen - 2]; // printing final result }
import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main (String[]args) { Scanner sc = new Scanner (System.in); System.out.print ("Enter size of array : "); int arrsize = sc.nextInt (); int[] main = new int[arrsize]; ArrayList < Integer > even = new < Integer > ArrayList (); ArrayList < Integer > odd = new < Integer > ArrayList (); System.out.println ("Enter " + arrsize + " Elements"); for (int i = 0; i < arrsize; i++) main[i] = sc.nextInt (); for (int i = 0; i < arrsize; i++) { if (i % 2 == 0) even.add (main[i]); else odd.add (main[i]); } Collections.sort (even); Collections.sort (odd); System.out.println ("Sorted even array "); for (int e:even) System.out.print (e + " "); System.out.println (); System.out.println ("sorted odd array "); for (int e:odd) System.out.print (e + " "); System.out.println (); int evensec = even.get (even.size () - 2); int oddsec = odd.get (odd.size () - 2); System.out.println ("Second Largest Element in Even List is:" + evensec); System.out.println ("Second Largest Element in Odd List is:" + oddsec); System. out.println ("Sum Of Second Largest Element Of Odd and Even List:" + (evensec + oddsec)); } }
array = [] evenArr = [] oddArr = [] n = int(input("Enter the size of the array:")) for i in range(0,n): number = int(input("Enter Element at {} index:".format(i))) array.append(number) if i % 2 == 0: evenArr.append(array[i]) else: oddArr.append(array[i]) evenArr = sorted(evenArr) print("Sorted Even Array:", evenArr[0:len(evenArr)]) oddArr = sorted(oddArr) print("Sorted Odd Array:", oddArr[0:len(oddArr)]) print(evenArr[1] + oddArr[1]) evenArr = sorted(evenArr) print("Sorted Even Array:", evenArr[0:len(evenArr)]) oddArr = sorted(oddArr) print("Sorted Odd Array:", oddArr[0:len(oddArr)]) print(evenArr[-2] + oddArr[-2])
Question 7 : Spiral Matrix
Problem Statement :
You will be given a 2d matrix. Write the code to traverse the matrix in a spiral format. Check the input and output for better understanding.
Sample Input :
Input :
5 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
Output :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <bits/stdc++.h> using namespace std; void Spiral(vector < vector < int >> a) { if (a.size() == 0) return; int m = a.size(), n = a[0].size(); int i, k = 0, l = 0; while (k < m && l < n) { for (i = l; i < n; ++i) cout << a[k][i] << " "; k++; for (i = k; i < m; ++i) cout << a[i][n - 1] << " "; n--; if (k < m) { for (i = n - 1; i >= l; --i) cout << a[m - 1][i] << " "; m--; } if (l < n) { for (i = m - 1; i >= k; --i) cout << a[i][l] << " "; l++; } } } int main() { int r, c; cin >> r >> c; vector < vector < int >> mat(r, vector < int > (c)); for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) cin >> mat[i][j]; Spiral(mat); }
import java.util.*; public class Main { public static List < Integer > solve(int [][]matrix,int row,int col) { List < Integer > res=new ArrayList < Integer > (); boolean[][] temp=new boolean[row][col]; int []arr1={0,1,0,-1}; int []arr2={1,0,-1,0}; int di=0,r=0,c=0; for(int i=0;i < row*col; i++) { res.add(matrix[r][c]); temp[r][c]=true; int count1=r+arr1[di]; int count2=c+arr2[di]; if(count1 >= 0 && row > count1 && count2 >= 0 && col > count2 && !temp[count1][count2]){ r=count1; c=count2; } else { di=(di+1)%4; r+=arr1[di]; c+=arr2[di]; } } return res; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int m=sc.nextInt(); int n=sc.nextInt(); int matrix[][]=new int[m][n]; for(int i=0;i < m;i++) { for(int j=0;j < n;j++) matrix[i][j]=sc.nextInt(); } System.out.println(solve(matrix,m,n)); } }
def spiralOrder(arr): ans = [] while arr: ans += arr.pop(0) arr = (list(zip(*arr)))[::-1] return ans arr = [] n, m = map(int, input().split()) for i in range(n): arr.append(list(map(int, input().split()))) print(*spiralOrder(arr))
Question 8 : Minimum Occurrence (R->Medium)
Problem Statement :
Given a sting , return the character that appears the minimum number of times in the string. The string will contain only ascii characters, from the ranges (“a”-”z”,”A”-”Z”,0-9), and case matters . If there is a tie in the minimum number of times a character appears in the string return the character that appears first in the string.
Input Format:
Single line with no space denoting the input string.
Output Format:
Single character denoting the least frequent character.
Constraints:
Length of string <=10^6
Sample Input:
cdadcda
Sample Output:
c
Explanation:
C and A both are with minimum frequency. So c is the answer because it comes first with less index.
#include <bits/stdc++.h> using namespace std; unordered_map < char,int > F; int main() { string s; int m=INT_MAX; cin >> s; for(auto i:s) F[i]++; for(auto i:F) m=min(m,i.second); for(auto i:s) if(F[i]==m) { cout << i; break; } }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String str=sc.next(); char arr[]=str.toCharArray(); int temp[]=new int[256]; for(int i=0;i < arr.length;i++) { temp[arr[i]]++; } int min=Integer.MAX_VALUE; int index=0; for(int i=255;i >= 0;i--) { if(temp[i]==0) continue; min=Math.min(min,temp[i]); } for(int i=0;i < arr.length;i++) { if(min==temp[arr[i]]) { System.out.println(arr[i]); break; } } } }
s=input() ans=[] for i in s: ans.append(s.count(i)) print(s[ans.index(min(ans))])
Question 9 : Sum of K Farthest items
Problem Statement :
You are given an array of length “len” ,another item called k and an integer value x. Your job is to find the sum of k farthest items in the array from x.
First line has len, k and x respectively
2nd line has the array
Example :
Input :
5 3 20
21 4 15 17 11
Output :
30
4, 15 and 11 are farthest from 20. Thus, their sum will be the answer.
#include <bits/stdc++.h> using namespace std; int main() { int len; cin >> len; int k; cin >> k; int x; cin >> x; vector < int > arr; for (int i = 0; i < len; i++) { int t; cin >> t; arr.push_back(t); } int max = INT_MIN; int sum = 0, index = -1; for (int i = 0; i < k; i++) { max = INT_MIN; for (int j = 0; j < len; j++) { if (arr[j] == INT_MIN) continue; int temp = abs(x - arr[j]); if (max < temp) { max = temp; index = j; } } //System.out.println(arr[index]); sum = sum + arr[index]; arr[index] = INT_MIN; } cout << sum; return 0; }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int len = sc.nextInt(); int k = sc.nextInt(); int x = sc.nextInt(); int arr[] = new int[len]; for (int i = 0; i < len; i++) arr[i] = sc.nextInt(); int max = Integer.MIN_VALUE; int sum = 0, index = -1; for (int i = 0; i < k; i++) { max = Integer.MIN_VALUE; for (int j = 0; j < len; j++) { if (arr[j] == Integer.MIN_VALUE) continue; int temp = (int) Math.abs(x - arr[j]); if (max < temp) { max = temp; index = j; } } sum = sum + arr[index]; arr[index] = Integer.MIN_VALUE; } System.out.println(sum); } }
len, k, x = map(int, input().split()) arr = list(map(int, input().split())) sum, index = 0, -1 for i in range(k): max = -9999999 for j in range(len): if arr[j] == -9999999: continue temp = abs(x - arr[j]) if max < temp: max = temp index = j sum = sum + arr[index] arr[index] = -9999999 print(sum)
Question 10: Match
Problem Statement :
The number of goals achieved by two football teams in matches in a league is given in the form of two lists. For each match of team B. Compute the total number of matches of team A where team A has scored less than or equal to the number of goals scored by team B in that match.
Example :
team A =[ 1,2,3]
team B =[ 2,4]
Team A has played three matches and has scored team A =[1,2,3] goals in each match respectively. Team B has played two matches and has scored team B = [2,4] goals in each match respectively. For 2 goals scored by team B in its first match, team A has 2 matches with scores 1,2 and 3 hence , the answer is [2,3].
Function Description :
Complete the function counts in the editor below.
Counts has the following parameters:
int teamA(n): First array of positive integers
int teamB(m): Second array of positive integers
Return :
int(m): an array of m positive integers, one for each teamB[i] representing the total number of elements from teamA[j] satisfying teamA[j]<_ teamB[i] where 0<_j<n and 0<_i< m, in the given order.
Constraints :
2<_n, m<_10^5
1<_ teamA[j]<_10^9,where 0<_j<n.
1<_ teamB[i]<_10^9,where 0<_j<m
Input format for custom Testing :
Input from stdin will be processed as follows and passed to the functions.
The first line contains an integer n, the number of elements in teamA.
The next n lines each contain an integer describing teamA[j] where 0<_j<n.
The next line contains an integer m, the number of elements in teamB.
The next m lines each contain an integer describing teamB[i]where 0<_i<m.
Sample input 0 :
4 -> teamA[] size n = 4
1 -> teamA = [1,4,2,4]
4
2
4
2-> teamB [] size m = 2
3-> teamB = [3,5]
5
Sample ōutput 0 :
2
4
Explanation 0 :
Given values are n =4, team A = [1,4,2,4], m= 2, and teamB = [3,5].
For teamB[0] = 3, we have 2 elements in teamA(teamA[0] = 1 and teamA[2] = 2) that are <_ teamB[0].
For teamB[1] = 5, we have 4 elements in teamA(teamA[0] = 1, teams[1] =4, teamA[2] = 2, and teamA[3] =4) that are <_teamB[1].
Thus , the function returns the array [2,4] as the answer.
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int teamA[] = new int[n]; for (int i = 0; i < n; i++) teamA[i] = sc.nextInt(); int m = sc.nextInt(); int teamB[] = new int[m]; for (int i = 0; i < m; i++) teamB[i] = sc.nextInt(); Arrays.sort(teamA); int count = 0; for (int i = 0; i < m; i++) { count = 0; for (int j = 0; j < n; j++) { if (teamA[j] <= teamB[i]) count++; else break; } System.out.println(count); } } }
ar=list(map(int,input().split())) br=list(map(int,input().split())) ar.sort() ans=[] import bisect for i in br: ans.append(bisect.bisect(ar,i)) print(ans)
#include <bits/stdc++.h> int main() { int n; std::cin >> n; int teamA[n]; for (int i = 0; i < n; i++) std::cin >> teamA[i]; int m; std::cin >> m; int teamB[m]; for (int i = 0; i < m; i++) std::cin >> teamB[i]; std::sort(teamA, teamA + n); int count = 0; for (int i = 0; i < m; i++) { count = 0; for (int j = 0; j < n; j++) { if (teamA[j] <= teamB[i]) count++; else break; } std::cout << count << std::endl; } return 0; }
FAQ's related Magicpin Hiring Process
Question 1: What kind of company is Magicpin?
MagicPin is a tool that helps people find great places to shop and enjoy different services. With its app, users can easily locate local cafes, dimsum spots, fashion boutiques, fancy spas, gyms, and even get discounts at grocery stores and more.
Question 2: What is the eligibility criteria for Magicpin hiring process?
Magicpin has set different eligibility criteria for SDE role and Analyst role such as:
- For SDE role :
- Minimum 8 C.G.P.A or Equivalent % throughout academic.
- B.Tech – CS, IT or ECE.
- No current backlog allowed.
- For Analyst role :
- Minimum 7.5 C.G.P.A or Equivalent % throughout academic.
- B.Tech – CS, IT or ECE.
- No current backlog allowed.
- Applicants must have good command in Python and SQL.
Question 3: What is the recruitment process of Magicpin?
Magicpin recruitment process includes following steps:
- Resume Shortlisting
- Online Assessment
- Technical Interview
- HR Interview
Question 4: What are the skills required for Analyst Intern in Magicpin?
For Magicpin Analyst Intern role you must have good knowledge in following skills:
- Python
- Advanced Excel
- SQL
- DBMS
Question 5: What is the salary in MagicPin?
- For Analyst Intern = On an average of ₹ 4.5 LPA to ₹ 6 LPA.
- For SDE Role = Ranges between ₹ 7 LPA to 11 LPA
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