DAA Codes 1
DAA Codes 1
1. Jump Game
You are given an integer array nums. You are initially positioned at the array's first
index, and each element in the array represents your maximum jump length at that
position.
Return true if you can reach the last index, or false otherwise.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Code:
class Solution {
public:
bool canJump(vector<int>& nums) {
int maxIdx = nums[0];
return true;
}
};
Solution:
2. Pascal’s Triangle
Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it
as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Code:
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>>ans;
map<pair<int,int>,int>mpp;
for(int row=0;row<numRows;row++)
{
vector<int>temp;
for(int col=0;col<=row;col++)
{
if(col==0 || col==row)
{
temp.push_back(1);
mpp[make_pair(row,col)]=1;
}
else
{
mpp[make_pair(row,col)]=mpp[make_pair(row-1,col-1)]
+mpp[make_pair(row-1,col)];
temp.push_back(mpp[make_pair(row,col)]);
}
}
ans.push_back(temp);
}
return ans;
}
};
Solutions:
Code:
class Solution {
public:
//total water is trapped into the bars
int trap(vector<int>& h) {
int l=0,r=h.size()-1,lmax=INT_MIN,rmax=INT_MIN,ans=0;
while(l<r){
lmax=max(lmax,h[l]);
rmax=max(rmax,h[r]);
ans+=(lmax<rmax)?lmax-h[l++]:rmax-h[r--];
}
return ans;
}
};
Solutions:
car travels from a starting position to a destination which is target miles east of the
starting position.
There are gas stations along the way. The gas stations are represented as an
array stations where stations[i] = [position , fuel ] indicates that the i gas station
i i
th
is position miles east of the starting position and has fuel liters of gas.
i i
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in
it. It uses one liter of gas per one mile that it drives. When the car reaches a gas
station, it may stop and refuel, transferring all the gas from the station into the car.
Return the minimum number of refueling stops the car must make in order to reach
its destination. If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there.
If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Code:
class Solution {
public:
int minRefuelStops(int target, int start_fuel, vector<vector<int>>&
stations) {
int n = stations.size();
priority_queue<int> pq;
int count = 0;
int i = 0;
i++;
}
// if pq is empty, then it is not possible to reach the target,
return -1
if(pq.empty())
return -1;
curr_dist += pq.top();
pq.pop();
count++;
}
return count;
}
};
Solutions:
Example 1:
Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: One possible path is [1,0,2,0,3]
Code:
class Solution {
public:
vector<vector<int>> dp;
int visitAll(int source, int n, int mask, vector<vector<int>> &dist){
if(dp[source][mask] != -1) return dp[source][mask];
for(int nbr=0;nbr<n;nbr++){
if((mask & (1<<nbr))) continue;
allVisited = false;
int cur = visitAll(nbr, n, mask + (1<<nbr), dist);
if(cur != INT_MAX) minDist = min(minDist, dist[source][nbr] +
cur);
}
// seen[source] = false;
if(allVisited) return dp[source][mask] = 0;
else return dp[source][mask] = minDist;
}
return result;
}
};
Solution:
BackTracking
6. Shopping offers
n LeetCode Store, there are n items to sell. Each item has a price. However, there
are some special offers, and a special offer consists of one or more different kinds of
items with a sale price.
You are given an integer array price where price[i] is the price of the i item, and an
th
integer array needs where needs[i] is the number of pieces of the i item you want to
th
buy.
You are also given an array special where special[i] is of size n + 1 where special[i][j] is the
number of pieces of the j item in the i offer and special[i][n] (i.e., the last integer in
th th
Return the lowest price you have to pay for exactly certain items as given, where
you could make optimal use of the special offers. You are not allowed to buy more
items than you want, even if that would lower the overall price. You could use any of
the special offers as many times as you want.
Example 1:
Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
Output: 14
Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.
Code:
class Solution {
public:
void find(vector<int>& price, vector<vector<int>>& special, vector<int>
&needs, int idx , int &mn_price , int Price){
mn_price = min(mn_price,Price);
if(idx==special.size()) return;
int n = needs.size();
// not take
find(price,special,needs,idx+1,mn_price,Price);
vector<int> needs2 = needs;
// new price calculation
for(int i = 0; i<n; i++){
if(needs2[i]<special[idx][i]) return;
Price = Price - special[idx][i]*price[i];
// update our needs
needs2[i] = needs2[i]-special[idx][i];
}
Price+= special[idx][n];
//take
find(price,special,needs2,idx,mn_price,Price);
}
int shoppingOffers(vector<int>& price, vector<vector<int>>& special,
vector<int>& needs) {
int mn_price = 0;
int n = price.size();
for(int i = 0; i<n; i++){
mn_price+= price[i]*needs[i];
}
map<vector<int>,int> mp;
for(auto &v : special){
vector<int> temp(v.begin(),v.end()-1);
if(mp.find(temp)==mp.end()) mp[temp] = v[v.size()-1];
else{
if(v[v.size()-1]<mp[temp]){
mp[temp] = v[v.size()-1];
}
}
}
special.clear();
for(auto &p : mp){
vector<int> temp = p.first;
temp.push_back(p.second);
special.push_back(temp);
}
find(price,special,needs,0,mn_price,mn_price);
return mn_price;
}
};
Solutions:
7. Beautiful arrangement
Suppose you have n integers labeled 1 through n. A permutation of
those n integers perm (1-indexed) is considered a beautiful arrangement if for
every i (1 <= i <= n), either of the following is true:
perm[i] is divisible by i.
i is divisible by perm[i].
Given an integer n, return the number of the beautiful arrangements that you
can construct.
Example 1:
Input: n = 2
Output: 2
Explanation:
The first beautiful arrangement is [1,2]:
- perm[1] = 1 is divisible by i = 1
- perm[2] = 2 is divisible by i = 2
The second beautiful arrangement is [2,1]:
- perm[1] = 2 is divisible by i = 1
- i = 2 is divisible by perm[2] = 1
Code:
class Solution {
public:
void solve(vector<int>& nums, int n, int& ans, int cur_num){
//base case
if(cur_num >= n+1){
ans++;
return;
}
//recursive relation
for(int j=1; j<=n; j++){
if(nums[j] == 0 && (cur_num % j == 0 || j % cur_num == 0)){
nums[j] = cur_num;
solve(nums, n, ans, cur_num+1);
//backtracking
nums[j] = 0;
}
}
}
int countArrangement(int n) {
vector<int> nums(n+1);
int ans = 0, ind = 1;
solve(nums, n, ans, ind);
return ans;
}
};
Solutions:
8. Birray Watch
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on
the bottom to represent the minutes (0-59). Each LED represents a zero or one, with
the least significant bit on the right.
For example, the below binary watch reads "4:51".
Given an integer turnedOn which represents the number of LEDs that are currently on
(ignoring the PM), return all possible times the watch could represent. You may
return the answer in any order.
The hour must not contain a leading zero.
For example, "01:00" is not valid. It should be "1:00".
The minute must consist of two digits and may contain a leading zero.
For example, "10:2" is not valid. It should be "10:02".
Example 1:
Input: turnedOn = 1
Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
Code:
class Solution {
public:
vector<string> readBinaryWatch(int turnedOn) {
vector<string> result;
for(int h=0;h<12;h++){
for(int m=0;m<60;m++){
if((__builtin_popcount(h)+__builtin_popcount(m))==turnedOn)
{
result.push_back(to_string(h)+(m<10 ? ":0" : ":")
+to_string(m));
}
}
}
return result;
}
};
Solutions:
Solution:
9. Fair distribution of cookies
You are given an integer array cookies, where cookies[i] denotes the number of cookies
in the i bag. You are also given an integer k that denotes the number of children to
th
distribute all the bags of cookies to. All the cookies in the same bag must go to the
same child and cannot be split up.
The unfairness of a distribution is defined as the maximum total cookies obtained
by a single child in the distribution.
Return the minimum unfairness of all distributions.
Example 1:
Input: cookies = [8,15,10,20,8], k = 2
Output: 31
Explanation: One optimal distribution is [8,15,8] and [10,20]
- The 1 st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.
- The 2 nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.
The unfairness of the distribution is max(31,30) = 31.
It can be shown that there is no distribution with an unfairness less than 31.
Code:
class Solution {
public:
int k, res = INT_MAX;
vector<int> d = {0, 0, 0, 0, 0, 0, 0, 0};
if (f < k) {
d[f] += cookies[index];
S(cookies, index + 1, f + 1);
d[f] -= cookies[index];
}
}
int distributeCookies(vector<int>& cookies, int K) {
k = K;
S(cookies, 0, 0);
return res;
}
};
Solutions:
The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if
the array is empty.
For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.
Given an array nums, return the sum of all XOR totals for every subset of nums.
Note: Subsets with the same elements should be counted multiple times.
An array a is a subset of an array b if a can be obtained from b by deleting some
(possibly zero) elements of b.
Example 1:
Input: nums = [1,3]
Output: 6
Explanation: The 4 subsets of [1,3] are:
- The empty subset has an XOR total of 0.
- [1] has an XOR total of 1.
- [3] has an XOR total of 3.
- [1,3] has an XOR total of 1 XOR 3 = 2.
0+1+3+2=6
Code:
class Solution {
public:
void solve(vector<vector<int>>&res,vector<int>ans,int i,vector<int>&
nums,int n){
if(i>=n){
res.push_back(ans);
return;
}
solve(res,ans,i+1,nums,n);
ans.push_back(nums[i]);
solve(res,ans,i+1,nums,n);
}
int subsetXORSum(vector<int>& nums) {
vector<vector<int>>res;
vector<int>ans;
int index=0;
int n=nums.size();
solve(res,ans,index,nums,n);
int sum=0;
int total=0;
for(int i=0;i<res.size();i++){
for(int j=0;j<res[i].size();j++){
total=total^res[i][j];
}
sum+=total;
total=0;
}
return sum;
}
};
Solutions: