WorksheetsMock Test OPJU
Total questions: 53
Worksheet time: 3hrs 13mins
Enter Your Name
Enter Your Enrolment
Enter Your Email ID
A man bought a bike at the marked price of Rs.65,000 with a discount of 3% on its
marked price. If the salesman makes 30% of profit on this sale then what will be the cost
price of the bike?(Directly mention the answer without comma or unit)
(a)
Two stations A and B are 110 km apart on a straight line. One train starts from A at 7 am
and travels towards B at 20 kmph. Another train starts from B at 8 am and
travels towards A at a speed of 25 kmph. At what time will they meet?(Directly Mention the result without comma or unit)
(a)
The average age of 8 persons is increased by 2 years, when two of them,
whose ages are 20 years and 24 years, are replaced by two women. What is
the average age of these women?(Directly Mention the result without comma or unit)
(a)
How much water be added to 14 litres of milk worth Rs. 5.40 a litre so that the
value of the mixture is Rs. 4.20 a litre?(Directly Mention the result without comma or unit)
(a)
Two pipes can fill a tank in 25 and 30 minutes respectively and a waste pipe
can empty 5 gallons per minute. All the three pipes working together can fill
the tank in 15 minutes. The capacity of the tank is in gallons?(Directly Mention the result without comma or unit)
(a)
Amar, Akbar and Anthony are working on a project. Working together Amar
and Akbar can complete the project in 1 year, Akbar and Anthony can
complete in 16 months, Anthony and Amar can complete in 2 years. If the
person who is neither the fastest nor the slowest works alone, the time in
months he will take to complete the project is?(Directly Mention the result without comma or unit)
(a)
A sum was put at simple interest at a certain rate of interest for 2 years. It
would have fetched Rs.72 more had it been put at 3% higher rate. What was
the sum?(Directly Mention the result without comma or unit)
(a)
The difference between the simple interest and the compound interest on Rs
5000 at 10% per annum for 2 yr is?(Directly Mention the result without comma or unit)
(a)
How many prime factors are there in 5040?(Directly Mention the result without comma or unit)
(a)
The LCM and HCF of two positive numbers is 400 and 40 respectively. If one
of the numbers is 200, what is the other number?(Directly Mention the result without comma or unit)
(a)
How many 3-digit numbers can be formed from the digits 2, 3, 5, 6, 7 and 9,
which are divisible by 5 and none of the digits is repeated?(Directly Mention the result without comma or unit)
(a)
In how many different ways can the letters of the word ‘MACHINE’ be
arranged so that the vowels may occupy only the odd positions?(Directly Mention the result without comma or unit)
(a)
A bag contains 4 white, 5 red and 6 green balls. Three balls are drawn at
random. What is the chance that a White, a red and a green ball is drawn?(Directly Mention the result without comma or unit)(Give Answer in x/y format)
(a)
if 12364×92×43=2a3b , then value of a and b will be?(Directly Mention the result without comma or unit)(Enter values of a and b as a_b)
(a)
P = 441 × 484 × 529 × 576 × 625. The total number of factors of P is?(Directly Mention the result without comma or unit)
(a)
Neeraj starts walking from point M towards east direction to reach N, which is 25m east to M. He
then takes a right turn and walks 30 m to reach point O. From O, he takes left turn and walks25m to
point P, then again, he takes a left turn and walks 20m to point Q. From Q, he takes a left turn and
walks 30m to reach point R. He then takes a right turn and walks 15m to reach S and finally takes a
left turn to reach point T, which is 20 m away from S.
In which direction is point N with respect to point R?(Answer in format such as west-east or west)
(a)
In the evening near to 4.30 p.m. when Ramakant was returning from his tuitions, he saw his
teacher coming in the opposite direction. His teacher talked to him for some time. Ramakant saw
that the shadow of his Teacher was to his right side. Which direction was his teacher facing during
their conversation?(Answer in format such as west-east or west)
(a)
A and B are brothers. C and D are sisters. A’s son is D’s brother. How is C related to B?
(a)
A is B’s wife and c is A’s sister. D is father of C, while E is D’s son. What is the relation of E to B?
(a)
In a certain code ‘BACKSPACE’ is written as ‘ABKCPSCAE’. How would ‘INSPIRONE’ be written in
that code?(Enter answer in all CAPS)
(a)
A cuboid shaped wooden block has 8 cm length, 4 cm breadth and 1 cm height.
Two faces measuring 4 cm x 1 cm are coloured in black.
Two faces measuring 8 cm x 1 cm are coloured in yellow.
Two faces measuring 8 cm x 4 cm are coloured in purple.
The block is divided into 8 equal cubes of side 1 cm (from 8 cm side), 4 equal cubes of side 1 cm(from
4 cm side).
How many small cubes will be formed?(Directly Mention the result without comma or unit)
(a)
Read the following information carefully and answer the questions given below:
Zika, Yisha, Xomi, Wara, Veta, Uma, Tani and Sipa are sitting around a circle facing the centre but not
necessarily in the same order.
Yisha sits second to the left of Sipa’s husband. No female is an immediate neighbour of
Yisha.
Wara’s daughter sits second to the right of Uma. Uma is the sister of Tani. Uma is not an
immediate neighbour of Sipa’s husband.
Only one person sits between Zika and Uma. Zika is father of Tani.
Sipa’s brother Wara sits on the immediate left of Sipa’s mother.
Only one person sits between Sipa’s mother and Veta.
Only one person sits between Sipa and Tani. Tani is the mother of Xomi. Tani is not an immediate
neighbour of Veta.
Who amongst the following is Wara’s daughter?
(a)
Arrange the words given below in a meaningful sequence.
1. Government Funding 2. Investment Plan 3. Selling 4. Budget plan 5. Inauguration 6. Shop Purchase
(a)
In a particular year 10th of 10th month was a Sunday In the same year 8th of 8th month falls on
which day of the week?
(a)
A bag contains red, blue, and green marbles.
1. The number of red marbles is twice the number of blue marbles.
2. The number of green marbles is 5 less than the number of red marbles.
Question to answer:
How many marbles are in the bag?
Statements given:
Statement 1: The total number of red and blue marbles is 21.
Statement 2: The total number of blue and green marbles is 19.
Options:
A) Statement 1 alone is sufficient, but Statement 2 alone is not.
B) Statement 2 alone is sufficient, but Statement 1 alone is not.
C) Both statements together are sufficient to answer the question.
D) Each statement alone is sufficient.
E) Even together, the statements are not sufficient.(Enter Answer in Single Alphabet without Special Symbol)
(a)
Error Detection:-
Although it was raining, but we went out?(Detect the error in the statement and type it)
(a)
One word substitution:-
Person who draws maps?
(a)
One word substitution:-
What do you call the group of owl
(a)
Rewrite concise sentence :-
what is your basic understanding of Predestination?
(a)
Para Jumble
A. The Himalayas shape the subcontinent’s climate patterns.
B. Beyond geography, the carry culture and spiritual weight.
C. They are the world’s highest mountain range.
D. Acting as a barrier, they block cold winds from the north
(a)
Sum of Digits
Question:
Given an integer n, find the sum of its digits.
Code:
#include <iostream>
using namespace std;
int main()
{
int n = 1234;
int sum = 0;
while (n > 0)
{
// TODO: Fill here
n /= 10;
}
cout << sum;
}
(a)
Reverse a Number
Question:
Reverse the digits of an integer n.
Code:
#include <iostream>
using namespace std;
int main() {
int n = 4321, rev = 0;
while (n > 0) {
// TODO: Fill here
n /= 10;
}
cout << rev;
}
(a)
Factorial
Question:
Find the factorial of a number n.
Code:
#include <iostream>
using namespace std;
int main() {
int n = 5;
long long fact = 1;
for (int i = 1; i <= n; i++) {
// TODO: Fill here
}
cout << fact;
}
(a)
Count Even Numbers in Array
Question:
Count how many even numbers are present in an array.
Code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 4, 7, 8, 10};
int n = 5, count = 0;
for (int i = 0; i < n; i++) {
// TODO: Fill here
}
cout << count;
}
(a)
Find Maximum Element in Array
Question:
Find the largest element in an array.
Code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {3, 8, 2, 10, 7};
int n = 5;
int maxVal = arr[0];
for (int i = 1; i < n; i++) {
// TODO: Fill here
}
cout << maxVal;
}
(a)
Check Prime
Question:
Check whether a number n is prime.
Code:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n = 17;
bool isPrime = true;
for (int i = 2; i <= sqrt(n); i++) {
// TODO: Fill here
}
cout << (isPrime ? "Prime" : "Not Prime");
}
(a)
Armstrong Number
Question:
Check whether a number is Armstrong (sum of cubes of digits = number).
Code:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n = 153, temp = n, sum = 0;
while (temp > 0) {
// TODO: Fill here
temp /= 10;
}
cout << (sum == n ? "Armstrong" : "Not Armstrong");
}
(a)
Fibonacci Series
Question:
Print first n terms of Fibonacci series.
Code:
#include <iostream>
using namespace std;
int main() {
int n = 5, a = 0, b = 1;
cout << a << " " << b << " ";
for (int i = 2; i < n; i++) {
int c = a + b;
cout << c << " ";
a = b;
// TODO: Fill here
}
}
(a)
Count Vowels in String
Question:
Count the number of vowels in a given string.
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "placement";
int count = 0;
for (char c : str) {
// TODO: Fill here
}
cout << count;
}
(a)
Sum of Array Elements
Question:
Find the sum of all elements in an array.
Code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {5, 10, 15, 20};
int n = 4, sum = 0;
for (int i = 0; i < n; i++) {
// TODO: Fill here
}
cout << sum;
}
(a)
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital. The answer is guaranteed to fit in a 32-bit signed integer.
Example 1: Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
Output: 4
Explanation: Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
Example 2: Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]
Output: 6
Constraints: 1 <= k <= 10^5
0 <= w <= 10^9
n == profits.length
n == capital.length
1 <= n <= 10^5
0 <= profits[i] <= 10^4
0 <= capital[i] <= 10^9
for (int i = 0; i < k; i++) {
while (idx < n && capital_profit[idx].first < w) {
maxHeap.push(capital_profit[idx].second);
idx++;
}
if (maxHeap.empty()) break;
w += maxHeap.top();
maxHeap.pop();
}
for (int i = 0; i < k; i++) {
while (idx < n && capital_profit[idx].first <= w) {
maxHeap.push(capital_profit[idx].second);
idx++;
}
if (maxHeap.empty()) break;
int profit = maxHeap.top();
maxHeap.pop();
w += maxHeap.empty() ? 0 : profit;
}
for (int i = 0; i < k; i++) {
while (idx < n && capital_profit[idx].first <= w) {
maxHeap.push(capital_profit[idx].first);
idx++;
}
if (maxHeap.empty()) break;
w += maxHeap.top();
maxHeap.pop();
}
for (int i = 0; i < k; i++) {
while (idx < n && capital_profit[idx].first <= w) {
maxHeap.push(capital_profit[idx].second);
idx++;
}
if (maxHeap.empty()) break;
w += maxHeap.top();
maxHeap.pop();
}
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "1 + 1" Output: 2
Example 2:
Input: s = " 2-1 + 2 " Output: 3
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)" Output: 23
Constraints:
1 <= s.length <= 3 * 105
s consists of digits, '+', '-', '(', ')', and ' '.
s represents a valid expression.
'+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
'-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
There will be no two consecutive operators in the input.
Every number and running calculation will fit in a signed 32-bit integer.
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i])) {
int num = 0;
while (i < s.size() && isdigit(s[i])) {
num = num * 10 + (s[i] - '0');
i++;
}
i--;
result += sign * num;
}
else if (s[i] == '+') sign = 1;
else if (s[i] == '-') sign = -1;
else if (s[i] == '(') {
st.push(result);
st.push(sign);
result = 0;
sign = 1;
}
else if (s[i] == ')') {
result = result * sign; // wrong
result += st.top(); st.pop();
st.pop(); // discards sign incorrectly
}
}
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i])) {
int num = 0;
while (i < s.size() && isdigit(s[i])) {
num = num * 10 + (s[i] - '0');
i++;
}
i--;
result += sign * num;
}
else if (s[i] == '+') sign = 1;
else if (s[i] == '-') sign = -1;
else if (s[i] == '(') {
st.push(result);
st.push(sign);
result = 0;
sign = 1;
}
else if (s[i] == ')') {
result = st.top() * result; st.pop();
result += st.top(); st.pop();
}
}
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i])) {
int num = 0;
while (i < s.size() && isdigit(s[i])) {
num = num * 10 + (s[i] - '0');
i++;
}
i--;
result += sign * num;
}
else if (s[i] == '+') sign = 1;
else if (s[i] == '-') sign = -1;
else if (s[i] == '(') {
st.push(result);
st.push(sign);
result = 0;
// missing sign reset here
}
else if (s[i] == ')') {
result = st.top() * result; st.pop();
result += st.top(); st.pop();
}
}
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i])) {
int num = 0;
while (i < s.size() && isdigit(s[i])) {
num = num * 10 + (s[i] - '0');
i++;
}
i--;
result += sign * num;
}
else if (s[i] == '+') sign = 1;
else if (s[i] == '-') sign = -1;
else if (s[i] == '(') {
st.push(sign); // wrong: sign pushed first
st.push(result);
result = 0;
sign = 1;
}
else if (s[i] == ')') {
result = st.top() * result; st.pop();
result += st.top(); st.pop();
}
}
RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element. Implement the RandomizedCollection class: RandomizedCollection() Initializes the empty RandomizedCollection object. bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise. bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them. int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains. You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.
Example 1: Input ["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] [[], [1], [1], [2], [], [1], []]
Output [null, true, false, true, 2, true, 1]
Explanation
RandomizedCollection randomizedCollection = new RandomizedCollection();
randomizedCollection.insert(1); // return true since the collection does not contain 1.
// Inserts 1 into the collection.
randomizedCollection.insert(1); // return false since the collection contains 1.
// Inserts another 1 into the collection. Collection now contains [1,1].
randomizedCollection.insert(2);
// return true since the collection does not contain 2.
// Inserts 2 into the collection. Collection now contains [1,1,2].
randomizedCollection.getRandom();
// getRandom should:
// - return 1 with probability 2/3, or
// - return 2 with probability 1/3.
randomizedCollection.remove(1);
// return true since the collection contains 1.
// Removes 1 from the collection. Collection now contains [1,2].
randomizedCollection.getRandom();
// getRandom should return 1 or 2, both equally likely. Constraints: -2^31 <= val <= 2^31 - 1 At most 2 * 10^5 calls in total will be made to insert, remove, and getRandom. There will be at least one element in the data structure when getRandom is called.
Implement the core logic for the remove(int val) function of the RandomizedCollection class so that it works in average O(1) time.
bool remove(int val) {
if (!idx.count(val)) return false;
int removeIdx = *idx[val].begin();
idx[val].erase(removeIdx);
int lastVal = nums.back();
nums[removeIdx] = lastVal;
idx[lastVal].insert(removeIdx);
idx[lastVal].erase(nums.size() - 1);
nums.pop_back();
if (idx[val].empty()) idx.erase(val);
return true;
}
bool remove(int val) {
if (!idx.count(val)) return false;
int removeIdx = *idx[val].begin();
idx[val].erase(removeIdx);
nums[removeIdx] = nums.back();
nums.pop_back();
idx[nums[removeIdx]].erase(nums.size());
if (idx[val].empty()) idx.erase(val);
return true;
}
bool remove(int val) {
if (!idx.count(val)) return false;
int removeIdx = *idx[val].begin();
idx[val].erase(removeIdx);
int lastVal = nums.back();
nums[removeIdx] = lastVal;
idx[lastVal].insert(removeIdx);
idx[lastVal].erase(nums.size());
nums.pop_back();
if (idx[val].empty()) idx.erase(val);
return true;
}
bool remove(int val) {
if (!idx.count(val)) return false;
int removeIdx = *idx[val].begin();
idx[val].erase(removeIdx);
int lastVal = nums.back();
nums[removeIdx] = lastVal;
idx[lastVal].insert(removeIdx);
idx[lastVal].erase(nums.size() - 1);
nums.pop_back();
return true;
}
You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word.
You are also given the helper object Master. You may call Master.guess(word) where word is a six-letter-long string, and it must be from words. Master.guess(word) returns:
-1 if word is not from words, or
an integer representing the number of exact matches (value and position) of your guess to the secret word.
There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word).
For each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get:
"Either you took too many guesses, or you did not find the secret word." if you called Master.guess more than allowedGuesses times or if you did not call Master.guess with the secret word, or
"You guessed the secret word correctly." if you called Master.guess with the secret word with the number of calls to Master.guess less than or equal to allowedGuesses.
The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method).
Example 1:
Input: secret = "acckzz", words = ["acckzz","ccbazz","eiowzz","abcczz"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist. master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches. master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches. master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches. master.guess("abcczz") returns 4, because "abcczz" has 4 matches. We made 5 calls to master.guess, and one of them was the secret, so we pass the test case.
Example 2:
Input: secret = "hamada", words = ["hamada","khaled"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: Since there are two words, you can guess both.
Constraints:
1 <= words.length <= 100
words[i].length == 6
words[i] consist of lowercase English letters.
All the strings of wordlist are unique.
secret exists in words.
10 <= allowedGuesses <= 30
class Solution {
public:
void findSecretWord(vector<string>& words, Master& master) {
for (int t = 0; t < 10; ++t) {
string guessWord = words[rand() % words.size()];
int matches = master.guess(guessWord);
vector<string> filtered;
for (auto &w : words) {
if (matchCount(guessWord, w) != matches) {
filtered.push_back(w);
}
}
words = filtered;
}
}
int matchCount(string &a, string &b) {
int cnt = 0;
for (int i = 0; i < 6; i++)
if (a[i] == b[i]) cnt++;
return cnt;
}
};
class Solution {
public:
void findSecretWord(vector<string>& words, Master& master) {
for (int t = 0; t < 10; ++t) {
string guessWord = words[rand() % words.size()];
int matches = master.guess(guessWord);
vector<string> filtered;
for (auto &w : words) {
if (matchCount(guessWord, w) == matches) {
filtered.push_back(w);
}
}
words = filtered;
}
}
int matchCount(string &a, string &b) {
int cnt = 0;
for (int i = 0; i < 6; i++)
if (a[i] == b[5 - i]) cnt++;
return cnt;
}
};
class Solution {
public:
void findSecretWord(vector<string>& words, Master& master) {
for (int t = 0; t < 10; ++t) {
string guessWord = words[rand() % words.size()];
int matches = master.guess(guessWord);
vector<string> filtered;
for (auto &w : words) {
if (matchCount(guessWord, w) == matches) {
filtered.push_back(w);
}
}
words = filtered;
}
}
int matchCount(string &a, string &b) {
int cnt = 0;
for (int i = 0; i < 6; i++)
if (a[i] == b[i]) cnt++;
return cnt;
}
};
class Solution {
public:
void findSecretWord(vector<string>& words, Master& master) {
for (int t = 0; t < 10; ++t) {
string guessWord = words[rand() % words.size()];
master.guess(guessWord);
words.pop_back();
}
}
};
There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
Choose some live pigs to feed.
For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.
Wait for minutesToDie minutes. You may not feed any other pigs during this time.
After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
Repeat this process until you run out of time.
Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.
Example 1:
Input: buckets = 4, minutesToDie = 15, minutesToTest = 15 Output: 2 Explanation: We can determine the poisonous bucket as follows: At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. At time 15, there are 4 possible outcomes: - If only the first pig dies, then bucket 1 must be poisonous. - If only the second pig dies, then bucket 3 must be poisonous. - If both pigs die, then bucket 2 must be poisonous. - If neither pig dies, then bucket 4 must be poisonous.
Example 2:
Input: buckets = 4, minutesToDie = 15, minutesToTest = 30 Output: 2 Explanation: We can determine the poisonous bucket as follows: At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. At time 15, there are 2 possible outcomes: - If either pig dies, then the poisonous bucket is the one it was fed. - If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.
Constraints:
1 <= buckets <= 1000
1 <= minutesToDie <= minutesToTest <= 100
#include <bits/stdc++.h>
using namespace std;
int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int trials = minutesToTest / minutesToDie;
int pigs = 0;
while (pow(trials, pigs) < buckets) {
pigs++;
}
return pigs;
}
int main() {
int buckets = 4, minutesToDie = 15, minutesToTest = 15;
cout << poorPigs(buckets, minutesToDie, minutesToTest) << endl;
}
#include <bits/stdc++.h>
using namespace std;
int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int trials = minutesToTest / minutesToDie + 1;
int pigs = 0;
while (pow(trials, pigs) < buckets) {
pigs++;
}
return pigs;
}
int main() {
int buckets = 4, minutesToDie = 15, minutesToTest = 15;
cout << poorPigs(buckets, minutesToDie, minutesToTest) << endl;
}
#include <bits/stdc++.h>
using namespace std;
int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int trials = minutesToTest / minutesToDie + 1;
int pigs = 0;
while (pow(trials, pigs) <= buckets) {
pigs++;
}
return pigs;
}
int main() {
int buckets = 4, minutesToDie = 15, minutesToTest = 15;
cout << poorPigs(buckets, minutesToDie, minutesToTest) << endl;
}
#include <bits/stdc++.h>
using namespace std;
int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int trials = minutesToTest / minutesToDie + 1;
int pigs = 0;
while (pow(trials - 1, pigs) < buckets) {
pigs++;
}
return pigs;
}
int main() {
int buckets = 4, minutesToDie = 15, minutesToTest = 15;
cout << poorPigs(buckets, minutesToDie, minutesToTest) << endl;
}
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 105
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n == 0) return 0;
vector<int> left(n, 0), right(n, 0);
int minPrice = prices[0];
for(int i = 1; i < n; i++) {
minPrice = min(minPrice, prices[i]);
left[i] = max(left[i-1], prices[i] - minPrice);
}
int maxPrice = prices[n-1];
for(int i = n-2; i >= 0; i--) {
maxPrice = max(maxPrice, prices[i]);
right[i] = max(right[i+1], maxPrice - prices[i]);
}
int maxProfit = 0;
for(int i = 0; i < n; i++) {
maxProfit = max(maxProfit, left[i] + right[i]);
}
return maxProfit;
}
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n == 0) return 0;
vector<int> left(n, 0), right(n, 0);
int minPrice = prices[0];
for(int i = 1; i < n; i++) {
minPrice = min(minPrice, prices[i]);
left[i] = max(left[i-1], prices[i] - minPrice);
}
int maxPrice = prices[n-1];
for(int i = n-2; i >= 0; i--) {
maxPrice = min(maxPrice, prices[i]);
right[i] = max(right[i+1], maxPrice - prices[i]);
}
int maxProfit = 0;
for(int i = 0; i < n; i++) {
maxProfit = max(maxProfit, left[i] + right[i]);
}
return maxProfit;
}
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n == 0) return 0;
vector<int> left(n, 0), right(n, 0);
int minPrice = prices[0];
for(int i = 1; i < n; i++) {
minPrice = min(minPrice, prices[i]);
left[i] = max(left[i-1], prices[i] - minPrice);
}
int maxPrice = prices[n-1];
for(int i = n-2; i >= 0; i--) {
maxPrice = max(maxPrice, prices[i]);
right[i] = max(right[i+1], maxPrice - prices[i]);
}
int maxProfit = 0;
for(int i = 0; i < n; i++) {
maxProfit = max(maxProfit, left[i] + left[i]);
}
return maxProfit;
}
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n == 0) return 0;
vector<int> left(n, 0), right(n, 0);
int minPrice = INT_MAX;
for(int i = 1; i < n; i++) {
minPrice = min(minPrice, prices[i]);
left[i] = max(left[i-1], prices[i] - minPrice);
}
int maxPrice = prices[n-1];
for(int i = n-2; i >= 0; i--) {
maxPrice = max(maxPrice, prices[i]);
right[i] = max(right[i+1], maxPrice - prices[i]);
}
int maxProfit = 0;
for(int i = 0; i < n; i++) {
maxProfit = max(maxProfit, left[i] + right[i]);
}
return maxProfit;
}
An array is squareful if the sum of every pair of adjacent elements is a perfect square.
Given an integer array nums, return the number of permutations of nums that are squareful.
Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i].
Example 1:
Input: nums = [1,17,8] Output: 2 Explanation: [1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: nums = [2,2,2] Output: 1
Constraints:
1 <= nums.length <= 12
0 <= nums[i] <= 109
#include <bits/stdc++.h>
using namespace std;
bool isSquare(int x) {
int r = sqrt(x);
return r * r == x;
}
int dfs(vector<int>& nums, vector<int>& used, int prev, int count) {
if (count == nums.size()) return 1;
int res = 0;
for (int i = 0; i < nums.size(); i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i-1] && !used[i-1]) continue;
if (prev == -1 || isSquare(prev + nums[i])) {
used[i] = 1;
res += dfs(nums, used, nums[i], count + 1);
used[i] = 1;
}
}
return res;
}
int numSquarefulPerms(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> used(nums.size(), 0);
return dfs(nums, used, -1, 0);
}
int main() {
vector<int> nums = {1,17,8};
cout << numSquarefulPerms(nums);
}
#include <bits/stdc++.h>
using namespace std;
bool isSquare(int x) {
int r = sqrt(x);
return r * r == x;
}
int dfs(vector<int>& nums, vector<int>& used, int prev, int count) {
if (count == nums.size()) return 1;
int res = 0;
for (int i = 0; i < nums.size(); i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i-1] && !used[i-1]) continue;
if (prev == -1 || !isSquare(prev + nums[i])) {
used[i] = 1;
res += dfs(nums, used, nums[i], count + 1);
used[i] = 0;
}
}
return res;
}
int numSquarefulPerms(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> used(nums.size(), 0);
return dfs(nums, used, -1, 0);
}
int main() {
vector<int> nums = {1,17,8};
cout << numSquarefulPerms(nums);
}
#include <bits/stdc++.h>
using namespace std;
bool isSquare(int x) {
int r = sqrt(x);
return r * r == x;
}
int dfs(vector<int>& nums, vector<int>& used, int prev, int count) {
if (count == nums.size()) return 1;
int res = 0;
for (int i = 0; i < nums.size(); i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i-1] && !used[i-1]) continue;
if (prev == -1 || isSquare(prev + nums[i])) {
used[i] = 1;
res += dfs(nums, used, nums[i], count + 1);
used[i] = 0;
}
}
return res;
}
int numSquarefulPerms(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> used(nums.size(), 0);
return dfs(nums, used, -1, 0);
}
int main() {
vector<int> nums = {1,17,8};
cout << numSquarefulPerms(nums);
}
#include <bits/stdc++.h>
using namespace std;
bool isSquare(int x) {
int r = sqrt(x);
return r * r == x;
}
int dfs(vector<int>& nums, vector<int>& used, int prev, int count) {
if (count == nums.size()) return 1;
int res = 0;
for (int i = 0; i < nums.size(); i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i-1] && !used[i-1]) continue;
if (prev == -1 || isSquare(abs(prev - nums[i]))) {
used[i] = 1;
res += dfs(nums, used, nums[i], count + 1);
used[i] = 0;
}
}
return res;
}
int numSquarefulPerms(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> used(nums.size(), 0);
return dfs(nums, used, -1, 0);
}
int main() {
vector<int> nums = {1,17,8};
cout << numSquarefulPerms(nums);
}
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.
If it is possible, return any [i, j] with i + 1 < j, such that:
arr[0], arr[1], ..., arr[i] is the first part,
arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and
arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.
All three parts have equal binary values.
If it is not possible, return [-1, -1].
Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.
Example 1:
Input: arr = [1,0,1,0,1] Output: [0,3]
Example 2:
Input: arr = [1,1,0,1,1] Output: [-1,-1]
Example 3:
Input: arr = [1,1,0,0,1] Output: [0,2]
Constraints:
3 <= arr.length <= 3 * 104
arr[i] is 0 or 1
#include <bits/stdc++.h>
using namespace std;
vector<int> threeEqualParts(vector<int>& arr) {
int n = arr.size();
int ones = 0;
for (int x : arr) ones += x;
if (ones == 0) return {0, n - 1};
if (ones % 3 != 0) return {-1, -1};
int k = ones / 3;
int first = -1, second = -1, third = -1, cnt = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
cnt++;
if (cnt == 1) first = i;
else if (cnt == k) second = i;
else if (cnt == 2 * k) third = i;
}
}
while (third < n && arr[first] == arr[second] && arr[third] == arr[first]) {
first++; second++; third++;
}
if (third == n) return {first - 1, second};
return {-1, -1};
}
#include <bits/stdc++.h>
using namespace std;
vector<int> threeEqualParts(vector<int>& arr) {
int n = arr.size();
int ones = 0;
for (int x : arr) ones += x;
if (ones == 0) return {0, n - 1};
if (ones % 3 != 0) return {-1, -1};
int k = ones / 3;
int first = -1, second = -1, third = -1, cnt = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
cnt++;
if (cnt == 1) first = i;
else if (cnt == k + 1) second = i;
else if (cnt == 2 * k + 1) third = i;
}
}
while (third < n && arr[first] == arr[second] && arr[third] == arr[first]) {
first++; second++; third++;
}
if (third == n) return {first - 1, second};
return {-1, -1};
}
#include <bits/stdc++.h>
using namespace std;
vector<int> threeEqualParts(vector<int>& arr) {
int n = arr.size();
int ones = 0;
for (int x : arr) ones += x;
if (ones == 0) return {0, n - 1};
if (ones % 3 != 0) return {-1, -1};
int k = ones / 3;
int first = -1, second = -1, third = -1, cnt = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
cnt++;
if (cnt == 1) first = i;
else if (cnt == k + 1) second = i;
else if (cnt == 2 * k + 1) third = i;
}
}
while (third < n && arr[first] == arr[second] && arr[third] == arr[first]) {
first++; second++; third++;
}
if (second == n) return {first - 1, second};
return {-1, -1};
}
#include <bits/stdc++.h>
using namespace std;
vector<int> threeEqualParts(vector<int>& arr) {
int n = arr.size();
int ones = 0;
for (int x : arr) ones += x;
if (ones == 0) return {0, n - 1};
if (ones % 3 != 0) return {-1, -1};
int k = ones / 3;
int first = -1, second = -1, third = -1, cnt = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
cnt++;
if (cnt == 1) first = i;
else if (cnt == k + 1) second = i;
else if (cnt == 2 * k + 1) third = i;
}
}
while (third < n && arr[first] == arr[second] && arr[third] == arr[first]) {
first++; second++; third++;
}
if (third == n) return {first, second};
return {-1, -1};
}
Given an integer array nums, return the number of AND triples.
An AND triple is a triple of indices (i, j, k) such that:
0 <= i < nums.length
0 <= j < nums.length
0 <= k < nums.length
nums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator.
Example 1:
Input: nums = [2,1,3]
Output: 12
Explanation: We could choose the following i, j, k triples: (i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
Example 2:
Input: nums = [0,0,0] Output: 27
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] < 216
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {2,1,3};
int n = nums.size();
int ans = 0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
int andVal = nums[i] & nums[j];
for(int k=0;k<n;k++){
if((andVal & nums[k]) == 0) ans++;
}
}
}
cout << ans;
}
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {2,1,3};
int n = nums.size();
int ans = 0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int k=0;k<n;k++){
if((nums[i] & nums[j] & nums[k]) == nums[i]) ans++;
}
}
}
cout << ans;
}
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {2,1,3};
int n = nums.size();
int ans = 0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
int andVal = nums[i] & nums[j];
for(int k=0;k<n;k++){
if((andVal & nums[k]) != 1) ans++;
}
}
}
cout << ans;
}
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {2,1,3};
int n = nums.size();
int ans = 0;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
int andVal = nums[i] & nums[j];
for(int k=0;k<n;k++){
if((andVal & nums[k]) == 0) ans++;
}
}
}
cout << ans;
}
You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:
1 <= pivot < n
nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]
You are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged.
Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.
Example 1:
Input: nums = [2,-1,2], k = 3 Output: 1 Explanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2]. There is one way to partition the array: - For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.
Example 2:
Input: nums = [0,0,0], k = 1 Output: 2 Explanation: The optimal approach is to leave the array unchanged. There are two ways to partition the array: - For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0. - For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.
Example 3:
Input: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33 Output: 4 Explanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14]. There are four ways to partition the array.
Constraints:
n == nums.length
2 <= n <= 105
-105 <= k, nums[i] <= 105
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<long long> nums = {2,-1,2};
long long k = 3;
int n = nums.size();
unordered_map<long long,int> right,left;
long long total = accumulate(nums.begin(),nums.end(),0LL);
long long sum = 0;
for(int i=0;i<n;i++){
sum += nums[i];
right[sum]++;
}
int ans = right[total/2]*(total%2==0);
sum = 0;
for(int i=0;i<n;i++){
long long diff = k - nums[i];
if(i>0){
sum += nums[i-1];
left[sum]++;
right[sum]--;
}
ans = max(ans, (left[total/2 - diff] + right[(total+diff)/2]) * ((total+diff)%2==0));
}
cout << ans;
}
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<long long> nums = {2,-1,2};
long long k = 3;
int n = nums.size();
unordered_map<long long,int> right,left;
long long total = accumulate(nums.begin(),nums.end(),0LL);
long long sum = 0;
for(int i=0;i<n-1;i++){
sum += nums[i];
right[sum]++;
}
int ans = right[total/2]*(total%2==0);
sum = 0;
for(int i=0;i<n;i++){
long long diff = nums[i] - k;
if(i>0){
sum += nums[i-1];
left[sum]++;
right[sum]--;
}
ans = max(ans, (left[total/2 - diff] + right[(total+diff)/2]) * ((total+diff)%2==0));
}
cout << ans;
}
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<long long> nums = {2,-1,2};
long long k = 3;
int n = nums.size();
unordered_map<long long,int> right,left;
long long total = accumulate(nums.begin(),nums.end(),0LL);
long long sum = 0;
for(int i=0;i<n-1;i++){
sum += nums[i];
right[sum]++;
}
int ans = right[total/2]*(total%2==0);
sum = 0;
for(int i=0;i<n;i++){
long long diff = k - nums[i];
if(i>0){
left[sum]++;
sum += nums[i-1];
right[sum]--;
}
ans = max(ans, (left[total/2 - diff] + right[(total+diff)/2]) * ((total+diff)%2==0));
}
cout << ans;
}
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<long long> nums = {2,-1,2};
long long k = 3;
int n = nums.size();
unordered_map<long long,int> right,left;
long long total = accumulate(nums.begin(),nums.end(),0LL);
long long sum = 0;
for(int i=0;i<n-1;i++){
sum += nums[i];
right[sum]++;
}
int ans = right[total/2]*(total%2==0);
sum = 0;
for(int i=0;i<n;i++){
long long diff = k - nums[i];
if(i>0){
sum += nums[i-1];
left[sum]++;
right[sum]--;
}
ans = max(ans, (left[total/2 - diff] + right[(total+diff)/2]) * ((total+diff)%2==0));
}
cout << ans;
}
