Salesforce Coding Questions and Answers
Salesforce Coding Questions with Solutions
Salesforce Coding Questions and Answers page will help you to get sample Coding Questions asked in the Online Assessment and Technical Interviews of Salesforce.
Go through this page to get all Sample Salesforce Coding Questions for preparing for Online Assessments and Technical Interviews of Salesforce.
Practice Salesforce Coding Questions and Answers Set 1
Question : 1
A taxi can take multiple passengers to the railway station at the same time.On the way back to the starting point,the taxi driver may pick up additional passengers for his next trip to the airport.A map of passenger location has been created,represented as a square matrix.
The Matrix is filled with cells,and each cell will have an initial value as follows:
- A value greater than or equal to zero represents a path.
- A value equal to 1 represents a passenger.
- A value equal to -1 represents an obstruction.
The rules of motion of taxi are as follows:
- The Taxi driver starts at (0,0) and the railway station is at (n-1,n-1).Movement towards the railway station is right or down,through valid path cells.
- After reaching (n-1,n-1) the taxi driver travels back to (0,0) by travelling left or up through valid path cells.
- When passing through a path cell containing a passenger,the passenger is picked up.once the rider is picked up the cell becomes an empty path cell.
- If there is no valid path between (0,0) and (n-1,n-1),then no passenger can be picked.
- The goal is to collect as many passengers as possible so that the driver can maximize his earnings.
For example consider the following grid,
0 1
-1 0
Start at top left corner.Move right one collecting a passenger. Move down one to the destination.Cell (1,0) is blocked,So the return path is the reverse of the path to the airport.All Paths have been explored and one passenger is collected.
Returns:
- Int:maximum number of passengers that can be collected.
Sample Input 0
- 4 -> size n = 4
- 4 -> size m = 4
- 0 0 0 1 -> mat
- 1 0 0 0
- 0 0 0 0
- 0 0 0 0
Output 0
- 2
Explanation 0
The driver can contain a maximum of 2 passengers by taking the following path
(0,0) → (0,1) → (0,2) → (0,3) → (1,3) → (2,3) → (3,3) → (3,2) → (3,1) → (3,0) → (2,0) → (1,0) → (0,0)
Sample Input 1
STD IN Function
———— ————-
- 3 → size n=3
- 3 → size m=3
- 0 1 -1 → mat
- 1 0 -1
- 1 1 1
Sample Output 1
- 5
Explanation 1
The driver can contain a maximum of 5 passengers by taking the following path
(0,0) → (0,1) → (1,1) → (2,1) → (2,2) → (2,1) → (2,0) → (1,0) → (0,0)
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 n, m; int mat[105][105]; map<pair<int, pair<int, int>>, int> dp; bool isValid(int i, int j) { if (mat[i][j] == -1) return false; if (i < 0 || i >= n) return false; if (j < 0 || j >= m) return false; return true; } int solve(int i, int j, int x, int y) { if (!isValid(i, j)) { return INT_MIN; } if (!isValid(x, y)) { return INT_MIN; } if (i == n - 1 && x == n - 1 && j == m - 1 && y == m - 1) { if (mat[i][j] == 1) { return 1; } else { return 0; } } if (dp.find({i, {j, x}}) != dp.end()) return dp[{i, {j, x}}]; int cur = 0; if (i == x && j == y) { if (mat[i][j] == 1) cur = 1; } else { if (mat[i][j] == 1) cur++; if (mat[x][y] == 1) cur++; } int op1 = solve(i + 1, j, x + 1, y); int op2 = solve(i, j + 1, x, y + 1); int op3 = solve(i + 1, j, x, y + 1); int op4 = solve(i, j + 1, x + 1, y); int ans = cur + max(op1, max(op2, max(op3, op4))); return dp[{i, {j, x}}] = ans; } int main() { cin >> n >> m; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> mat[i][j]; int ans = solve(0, 0, 0, 0); if (ans >= 0) cout << solve(0, 0, 0, 0) << endl; else cout << -1 << endl; return 0; }
import java.util.*; class Main { public static int cost(int grid[][], int row1, int col1, int row2, int col2) { if (row1 == row2 && col1 == col2) { if (grid[row1][col1] == 1) return 1; return 0; } int ans = 0; if (grid[row1][col1] == 1) ans++; if (grid[row2][col2] == 1) ans++; return ans; } public static int solve(int n, int m, int grid[][], int dp[][][], int row1, int col1, int row2) { int col2 = (row1 + col1) - (row2); if (row1 == n - 1 && col1 == m - 1 && row2 == n - 1 && col2 == m - 1) return 0; if (row1 >= n || col1 >= m || row2 >= n || col2 >= m) return -1 * Integer.MAX_VALUE; if (dp[row1][col1][row2] != -1) return dp[row1][col1][row2]; int ch1 = -1 * Integer.MAX_VALUE, ch2 = -1 * Integer.MAX_VALUE; int ch3 = -1 * Integer.MAX_VALUE, ch4 = -1 * Integer.MAX_VALUE; if (grid[row1][col1 + 1] != -1 && grid[row2 + 1][col2] != -1) ch1 = cost(grid, row1, col1 + 1, row2 + 1, col2) + solve(n, m, grid, dp, row1, col1 + 1, row2 + 1); if (grid[row1][col1 + 1] != -1 && grid[row2][col2 + 1] != -1) ch2 = cost(grid, row1, col1 + 1, row2, col2 + 1) + solve(n, m, grid, dp, row1, col1 + 1, row2); if (grid[row1 + 1][col1] != -1 && grid[row2][col2 + 1] != -1) ch3 = cost(grid, row1 + 1, col1, row2, col2 + 1) + solve(n, m, grid, dp, row1 + 1, col1, row2); if (grid[row1 + 1][col1] != -1 && grid[row2 + 1][col2] != -1) ch4 = cost(grid, row1 + 1, col1, row2 + 1, col2) + solve(n, m, grid, dp, row1 + 1, col1, row2 + 1); return dp[row1][col1][row2] = Math.max(ch1, Math.max(ch2, Math.max(ch3, ch4))); } public static void initializeDp(int dp[][][], int item) { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) for (int k = 0; k < 5; k++) dp[i][j][k] = item; } } public static int collectMax(int n, int m, int grid[][]) { int ans = 0; int dp[][][] = new int[6][6][6]; initializeDp(dp, -1); if (grid[n - 1][m - 1] == -1 || grid[0][0] == -1) ans = -1 * Integer.MAX_VALUE; if (grid[0][0] == 1) ans++; grid[0][0] = 0; if (grid[n - 1][m - 1] == 1) ans++; grid[n - 1][m - 1] = 0; ans += solve(n, m, grid, dp, 0, 0, 0); return Math.max(ans, 0); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int arr[][] = new int[n + 1][m + 1]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) arr[i][j] = sc.nextInt(); System.out.println(collectMax(n, m, arr)); } }
Question 2 :
Problem Statement -:
In an airport, the Airport authority decides to charge a minimum amount to the passengers who are carrying luggage with them. They set a threshold weight value, say, T, if the luggage exceeds the weight threshold you should pay double the base amount. If it is less than or equal to threshold then you have to pay $1.
Function Description:
Complete the weightMachine function in the editor below. It has the following parameter(s):
Parameters:
Name | Type | Description |
N | Integer | number of luggage |
T | Integer | weight of each luggage |
weights[ ] | Integer array | threshold weight |
Returns: The function must return an INTEGER denoting the required amount to be paid.
Constraints:
- 1 <= N <= 10^5
- 1 <= weights[i] <= 10^5
- 1 <= T <= 10^5
Input Format for Custom Testing:
- The first line contains an integer, N, denoting the number of luggage.
- Each line i of the N subsequent lines (where 0 <= i <n) contains an integer describing the weight of ith luggage.
- The next line contains an integer, T, denoting the threshold weight of the boundary wall.
Sample Cases:
- Sample Input 1
4
1
2
3
4
3 - Sample Output 1
5 - Explanation:
Here all weights are less than threshold weight except the luggage with weight 4 (at index 3) so all pays base fare and it pays double fare.
#include<stdio.h> #include<string.h> long int weightMachine(long int N,long int weights[],long int T) { long int amount=0,i; for(i=0;i<N;i++) { amount++; if(weights[i]>T) { amount++; } } return amount; } int main() { long int N,i,T; scanf("%ld",&N); long int weights[N]; for(i=0;i<N;i++) { scanf("%ld",&weights[i]); } scanf("%ld",&T); printf("%ld",weightMachine(N,weights,T)); return 0; }
#include <bits/stdc++.h> using namespace std; long int weightMachine(long int N,long int weights[],long int T) { long int amount=0,i; for(i=0;i<N;i++) { amount++; if(weights[i]>T) { amount++; } } return amount; } int main() { long int N,i,T; cin>>N; long int weights[N]; for(i=0;i<N;i++) { cin>>weights[i]; } cin>>T; cout<<weightMachine(N,weights,T); return 0; }
import java.util.*; class Main { static int weightMachine (int N, int weights[],int T) { int amount = 0, i; for (i = 0; i < N; i++) { amount++; if (weights[i] > T) { amount++; } } return amount; } public static void main (String[]args) { Scanner sc = new Scanner (System.in); int n = sc.nextInt (); int weights[]= new int[n]; for(int i=0; i<n; i++) weights[i] = sc.nextInt(); int t = sc.nextInt (); System.out.println (weightMachine(n, weights, t)); } }
def weightMachine(N,weights,T): amount=0 for i in weights: amount+=1 if(i>T): amount+=1 return amount N=int(input()) weights=[] for i in range(N): weights.append(int(input())) T=int(input()) print(weightMachine(N,weights,T))
Question 3:
Given two strings, s, and sub, along with a 2D character array mappings, we want to determine if it is possible to make the sub a substring of s by replacing characters according to the provided mappings. Each mapping consists of a pair [oldi, newi], indicating that we can replace the character oldi in sub with newi.
The replacement can be performed any number of times, but each character in sub can be replaced at most once.
We need to return true if it is possible to create sub as a substring of s using the given replacements, and false otherwise.
Example 1:
Input:
s = “fool3e7bar”
sub = “leet”
mappings = [[“e”,”3″],[“t”,”7″],[“t”,”8″]]
Output: True
Explanation:
We replace the first occurrence of ‘e’ in sub with ‘3’ and ‘t’ in sub with ‘7’, resulting in sub becoming “l3e7”. Now, “l3e7” is a substring of s, so we return true.
Example 2:
Input:
s = “fooleetbar”
sub = “f00l”
mappings = [[“o”,”0″]]
Output: False
Explanation:
The string “f00l” is not a substring of s, and no replacements can be made to create it. Additionally, we cannot replace ‘0’ with ‘o’, so it is not possible to create sub from s. Hence, we return false.
Example 3:
Input:
s = “Fool33tbaR”
sub = “leetd”
mappings = [[“e”,”3″],[“t”,”7″],[“t”,”8″],[“d”,”b”],[“p”,”b”]]
Output: True
Explanation:
We replace the first and second occurrences of ‘e’ in sub with ‘3’ and ‘d’ in sub with ‘b’, respectively. This transforms sub into “l33tb”, which is a substring of s. Therefore, we return true.
Constraints:
1 <= sub.length <= s.length <= 5000
0 <= mappings.length <= 1000
mappings[i].length == 2
oldi != newi
Both s and sub consist of uppercase and lowercase English letters and digits.
oldi and newi are either uppercase or lowercase English letters or digits.
#include<bits/stdc++.h> using namespace std; class Solution { public: vector compute_lps(string& s, unordered_map<char, unordered_set>& m) { vector lps(s.size()); for (int i = 1, j = 0; i < s.size(); ++i) { while (j && (s[i] != s[j] && m[s[i]].count(s[j]) == 0 && m[s[j]].count(s[i]) == 0)) j = max(0, lps[j] - 1); j += s[i] == s[j] || m[s[i]].count(s[j]) || m[s[j]].count(s[i]); lps[i] = j; } return lps; } bool matchReplacement(string s, string sub, vector<vector>& mappings) { unordered_map<char, unordered_set> m; for (auto& p : mappings) m[p[0]].insert(p[1]); auto lps = compute_lps(sub, m); for (int i = 0, j = 0; i < s.size();) { if (s[i] == sub[j] || m[sub[j]].count(s[i])) { ++i; ++j; } else { if (j != 0) j = lps[j - 1]; else i = i + 1; } if (j == sub.size()) return true; } return false; } }; int main() { Solution solution; // Example usage: // string s = "fool3e7bar"; // string sub = "leet"; // vector<vector> mappings = {{'e','3'}, {'t','7'}, {'t','8'}}; // string s = "fooleetbar"; // string sub = "f00l"; // vector<vector> mappings = {{'o','0'}}; string s = "Fool33tbaR"; string sub = "leetd"; vector<vector> mappings = {{'e','3'}, {'t','7'}, {'t','8'}, {'d','b'}, {'p','b'}}; bool result = solution.matchReplacement(s, sub, mappings); cout << boolalpha << result << endl; // Output: true return 0; }
class Solution: def compute_lps(self, s, m): lps = [0] * len(s) j = 0 for i in range(1, len(s)): while j > 0 and (s[i] != s[j] and (s[i] not in m or s[j] not in m[s[i]])): j = lps[j - 1] j += int(s[i] == s[j] or (s[i] in m and s[j] in m[s[i]])) lps[i] = j return lps def matchReplacement(self, s, sub, mappings): m = {} for p in mappings: if p[0] not in m: m[p[0]] = set() m[p[0]].add(p[1]) lps = self.compute_lps(sub, m) i, j = 0, 0 while i < len(s): if s[i] == sub[j] or (sub[j] in m and s[i] in m[sub[j]]): i += 1 j += 1 else: if j != 0: j = lps[j - 1] else: i += 1 if j == len(sub): return True return False solution = Solution() # Example usage: s = "fool3e7bar" sub = "leet" mappings = [['e', '3'], ['t', '7'], ['t', '8']] # s = "fooleetbar" # sub = "f00l" # mappings = [['o', '0']] # s = "Fool33tbaR" # sub = "leetd" # mappings = [['e', '3'], ['t', '7'], ['t', '8'], ['d', 'b'], ['p', 'b']] result = solution.matchReplacement(s, sub, mappings) print(result) # Output: True
class Main { public boolean matchReplacement(String s, String sub, char[][] mappings) { int m = sub.length(), n = s.length(); final int RANGE = 'z' - '0' + 1; boolean[][] multiMap = new boolean[RANGE][RANGE]; for (char[] map : mappings) { char from = map[0], to = map[1]; multiMap[from - '0'][to - '0'] = true; } // Now, we use a naive string matching algorithm // This will run in O(mn) time. for (int i = 0; i < n - m + 1; i++) { int j = 0; while (j < m) { char sc = s.charAt(i + j), subc = sub.charAt(j); if (sc != subc && !multiMap[subc - '0'][sc - '0']) break; j++; } if (j == m) return true; } return false; } public static void main(String[] args) { Main main = new Main(); // Example usage: // String s = "fool3e7bar"; // String sub = "leet"; // char[][] mappings = { { 'e', '3' }, { 't', '7' }, { 't', '8' } }; // String s = "fooleetbar"; // String sub = "f00l"; // char[][] mappings = { { 'o', '0' } }; String s = "Fool33tbaR"; String sub = "leetd"; char[][] mappings = { { 'e', '3' }, { 't', '7' }, { 't', '8' }, { 'd', 'b' }, { 'p', 'b' } }; boolean result = main.matchReplacement(s, sub, mappings); System.out.println(result); // Output: true } }
Question 4:
Problem Statement :
Suppose you are in a number system, where if the number doesn’t contain 2 in the unit digit then the number is not valid. So the first number of the number system is 2, the second number is 12, and the third is 22.
for a given integer n, you have to print the nth element of the number system.
Input Format:
First line, containing n denoting the number of test cases.
then n number of lines for the query.
Output Format:
Print the consecutive number in the number system for each query.
Sample Input:
3
Sample Output:
22
Explanation:
1st number will be 2 , 2nd number will be 12 and third number will be 32
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; cout << (n - 1) * 10 + 2; return 0; }
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); System.out.println((n - 1) * 10 + 2); } }
n = int(input()) print((n - 1) * 10 + 2)
Question 5:
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.
#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 PrepInsta { 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()))c++ for i in range(n-1): diff.append(arr[i+1]-arr[i]) ans=func(diff) if ans < 0: print("0") else: print(ans)
Practice Salesforce Coding Questions and Answers Set 2
Question 6:
Problem Statement :
Ratul made a linked list, a list made of n nodes, where every node has two variables, the velocity and the mass of a particle.
Since all the particles have the velocity in the same direction, find the total momentum of the entity made by the particles from the linked list.
Constraints :
1<=n<=10000
1<=m,v<=100
Input format:
First line containing n, number of nodes
Then n lines containing the mass and the velocity space separated.
Output Format:
Single integer denoting the momentum
Sample Input:
4
1 3
2 4
2 3
4 5
Sample Output:
37
#include <bits/stdc++.h> using namespace std; int main() { int n, s = 0, m, v; cin >> n; for (int i = 0; i < n; i++) { cin >> m >> v; s += (m * v); } cout << s; }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int s = 0; for (int i = 0; i < n; i++) { int m = sc.nextInt(); int v = sc.nextInt(); s += (m * v); } System.out.println(s); } }
n = int(input()) s = 0 for i in range(n): m, v = map(int, input().split()) s += m * v print(s)
Question 7:
Problem Statement :
Ashish was copying from Rahit in the exam. So, Rahit told him to change the answers a little bit so that the examiner cannot find the fraud. But silly Ashish in the way started to change all the answers that were needed. He shuffled the letters in each word in a way where the maximum number of letters were misplaced.
For a given word, find the maximum difference that Ashish can generate between his answer and Rahit’s answer.
Suppose Rahit wrote “car” for an answer, Ashish can write “acr” with difference 2, or “arc” with differnece 3.
Note That: The letters are all in lowercase.
Input Format:
First line containing an integer n, number of words.
Then, n numbers of lines as the query words.
Output:
N number of lines with an integer each denoting possible maximum difference.
Sample Input:
4
abababa
bbj
kj
kk
Sample Output:
6
2
2
0
#include<bits/stdc++.h> using namespace std; string s, s1; int n; int func() { if (n <= 1) return 0; int ans = 0, c = 0; sort(s.begin(), s.end()); for (int i = 0; i < n; i++) if (s1[i] != s[i]) c++; ans = max(ans, c); c = 0; while (next_permutation(s.begin(), s.end())) { for (int i = 0; i < n; i++) if (s1[i] != s[i]) c++; ans = max(ans, c); c = 0; } return ans; } int main() { int t; cin >> t; while (t--) { cin >> s; s1 = s; n = s.length(); cout << func() << endl; } return 0; }
import java.util.*; class Main { public static String swapString(String s, int i, int j) { char[] b = s.toCharArray(); char temp; temp = b[i]; b[i] = b[j]; b[j] = temp; return String.valueOf(b); } public static void generatePermutation(String s, int start, int end, HashSet < String > set) { if (start == end - 1) set.add(s + " "); else { for (int i = start; i < end; i++) { s = swapString(s, start, i); generatePermutation(s, start + 1, end, set); s = swapString(s, start, i); } } } public static int maxDiff(String str, String s) { int c = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == str.charAt(i)); else c++; } return c; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = sc.next(); } for (int i = 0; i < n; i++) { HashSet < String > set = new HashSet < String > (); String s = a[i]; generatePermutation(s, 0, s.length(), set); int max = 0; int k = 0; for (String str: set) { k = maxDiff(str, s); max = Math.max(max, k); } System.out.println(max); } } }
from itertools import permutations def solve(x, n): ans = 0 for i in permutations(x): c = 0 for j in range(n): if x[j] != i[j]: c += 1 ans = max(ans, c) return ans t = int(input()) for i in range(t): s = input() print(solve(s, len(s)))
Question 8:
Problem Statement :
A company has a list of jobs to perform. Each job has a start time, end time and profit value. The manager has asked his employee Anirudh to pick jobs of his choice. Anirudh being greedy wants to select jobs for him in such a way that would maximize his earnings.
Given a list of jobs how many jobs and total earning are left for other employees once Anirudh
Picks jobs of his choice.
Note: Anirudh can perform only one job at a time.
Input format:
Each Job has 3 pieces of info – Start Time,End Time and Profit
The first line contains the number of Jobs for the day. Say ‘n’. So there will be ‘3n lines
following as each job has 3 lines.
Each of the next ‘3n’ lines contains jobs in the following format:
start_time
end-time
Profit
start-time and end-time are in HHMM 24HRS format
i.e. 9am is 0900 and 9PM is 2100
Constraints :
The number of jobs in the day i.e’ is less.
than 10000
0<_n<_10000
start-time is always less than end time.
Output format :
Program should return an array of 2 integers where
1st one is number of jobs left and earnings of other employees
Sample Input 1 :
4
0200
0300
10
0400
0700
20
0300
0800
30
0900
1000
50
Sample Output 1:
1
20
Sample Explanation 1
CHooses 1st, 3rd and 4th job cause they don’t overlap. So only second job is remaining.
Sample Input 2:
5
0805
0830
100
0835
0900
100
0905
0930
100
0935
1000
100
1005
1030
100
Sample output 2:
0
0
Sample Explanation 2:
Anirudh can work on all appointments as there are none overlapping.
Hence 0 appointments and 0 earnings for other employees.
#include <bits/stdc++.h> using namespace std; class job { public: int st, ed, cost; }; int getTime(string s) { int hr = (s[0] - '0') * 10 + (s[1] - '0'); int min = (s[2] - '0') * 10 + (s[3] - '0'); return hr * 60 + min; } bool compare(job A, job B) { return A.ed < B.ed; } int searchJob(job arr[], int st, int ed, int key) { int ans = -1; while (st <= ed) { int mid = (st + ed) / 2; if (arr[mid].ed <= key) { ans = mid; st = mid + 1; } else { ed = mid - 1; } } return ans; } pair < int, int > solve(job arr[], int n) { int dp[n] = { 0 }; int numOfJobs[n] = { 0 }; dp[0] = arr[0].cost; numOfJobs[0] = 1; for (int i = 1; i < n; i++) { int cur = arr[i].cost; int num = 1; int idx = searchJob(arr, 0, i - 1, arr[i].st); if (idx != cur) { cur += dp[idx]; num += numOfJobs[idx]; } if (cur > dp[i - 1]) { dp[i] = cur; numOfJobs[i] = num; } else { dp[i] = dp[i - 1]; numOfJobs[i] = numOfJobs[i - 1]; } } return { numOfJobs[n - 1], dp[n - 1] }; } int main() { int n; cin >> n; job arr[n]; int cost; string st, ed; int total = 0; for (int i = 0; i < n; i++) { cin >> st >> ed >> cost; arr[i].st = getTime(st); arr[i].ed = getTime(ed); arr[i].cost = cost; total += cost; } sort(arr, arr + n, compare); pair < int, int > res = solve(arr, n); cout << n - res.first << endl; cout << total - res.second << endl; return 0; }
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; class Job { public Integer st; public Integer ed; public Integer cost; public Job() { super(); } public Job(Integer st, Integer ed, Integer cost) { super(); this.st = st; this.ed = ed; this.cost = cost; } } class Pair { public Integer first; public Integer second; public Pair() { super(); } public Pair(Integer first, Integer second) { super(); this.first = first; this.second = second; } } class SortingJobs implements Comparator < Job > { @Override public int compare(Job o1, Job o2) { if (o1.ed < o2.ed) { return 1; } else { return 0; } } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Job[] arr = new Job[n]; int cost; String st, ed; int total = 0; for (int i = 0; i < n; i++) { st = sc.next(); ed = sc.next(); if (st.length() < 4) { while (st.length() != 4) { st += "0"; } } if (ed.length() < 4) { while (ed.length() != 4) { ed += "0"; } } cost = sc.nextInt(); arr[i] = new Job(); arr[i].st = getTime(st); arr[i].ed = getTime(ed); arr[i].cost = cost; total += cost; } Arrays.sort(arr, new SortingJobs()); Pair res = new Pair(); res = solve(arr, n); if (res == null) { System.out.println(0); } else { System.out.println(n - res.first); System.out.println(total - res.second); } } private static Pair solve(Job[] arr, int n) { if (n == 0) { return null; } int dp[] = new int[n]; int numOfJobs[] = new int[n]; for (int i = 0; i < n; i++) { dp[i] = 0; numOfJobs[i] = 0; } dp[0] = arr[0].cost; numOfJobs[0] = 1; for (int i = 1; i < n; i++) { int curr = arr[i].cost; int num = 1; int idx = searchJob(arr, 0, i - 1, arr[i].st); if (idx != curr && idx != -1) { curr += dp[idx]; num += numOfJobs[idx]; } if (curr > dp[i - 1]) { dp[i] = curr; numOfJobs[i] = num; } else { dp[i] = dp[i - 1]; numOfJobs[i] = numOfJobs[i - 1]; } } return new Pair(numOfJobs[n - 1], dp[n - 1]); } private static int searchJob(Job[] arr, int st, int ed, int key) { int ans = -1; while (st <= ed) { int mid = (st + ed) / 2; if (arr[mid].ed <= key) { ans = mid; st = mid + 1; } else { ed = mid - 1; } } return ans; } private static int getTime(String st) { int hr = (st.charAt(0) - '0') * 10 + (st.charAt(1) - '0'); int min = (st.charAt(2) - '0') * 10 + (st.charAt(3) - '0'); return hr * 60 + min; } }
Question 9:
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
Question 10:
After Watching a movie at PVR, Adil is pondering over the number of ways in which he can pay for the movie. He has x1, x2, x3, x4 coins of values 1,2,5 and 10 respectively. He wants to determine the number of ways in which he can pay an amount A.
You need to fill in a function that returns the number of ways to pay total amount
Input Specifications:
Input 1: An integer value denoting the total amount to be paid
Output Specification:
Return an Integer value denoting the number of ways to pay the total amount
Example1:
Input1: 40
Output : 195
Example2:
Input1: 4
Output : 3
#include<bits/stdc++.h> using namespace std; int coinsExchange(int amt, int *deno, int n, int *dp) { // base case if (amt == 0) { return dp[amt] = 0; } if (dp[amt] != -1) { return dp[amt]; } // recursive case int ans = INT_MAX; for (int i = 0 ; i < n ; i++) { if (amt >= deno[i]) { int sa = coinsExchange(amt - deno[i], deno, n, dp); if (sa != INT_MAX) { ans = min(sa + 1, ans); } } } return dp[amt] = ans; } int main() { int deno[4] = {1, 2, 5, 10}; int amt; cin>>amt; int *dp = new int[amt + 1]; for (int i = 0 ; i <= amt ; i++) { dp[i] = -1; } cout << coinsExchange(amt, deno, 4, dp) << endl; return 0; }
import java.io.*; import java.util.*; public class Coin { static int count( int S[], int m, int n ) { if (n == 0) return 1; if (n < 0) return 0; if (m <=0 && n >= 1) return 0; return count( S, m - 1, n ) + count( S, m, n-S[m-1] ); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int total = sc.nextInt(); int arr[] = {1, 2, 5,10}; int m = arr.length; System.out.println( count(arr, m, total)); } }
FAQs related to Salesforce Coding Questions
Question 1: How many rounds are there in Salesforce Recruitment Process?
After, 1st Round (i.e. Coding Assessment) 3 Rounds of Technical Interviews are conducted depending on the job profile (i.e. Technical Interview includes DSA based Questions Solving and Computer Science Fundamentals), followed by H.R Interview.
Question 2: Is Coding questions asked in Salesforce Recruitment Process?
Yes, 1st Round of Online Assessment and all 3 Technical Interviews includes Coding Questions.
Question 3: What is the Eligibility Criteria for the Salesforce Recruitment Process?
There is No Minimum Eligibility Criteria throughout the academics.
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