LeetCode 1052 ( Grumpy BookStoreOwner ) - How to build algorithms from brute force to effecient

preview_player
Показать описание
In this video we explore to make an efficient algorithm working from having a brute force solution to the most optimal solution.

Рекомендации по теме
Комментарии
Автор

Thanks for the solution. Seems a pretty trivial sliding window solution at first. Thanks for intriducing the thought process

psn
Автор

Solution in C++;
class Solution {
public:
int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes) {
int sum = 0;
int i = 0;
int j = 0;
int maxsum = INT_MIN;
for (int i = 0 ; i < grumpy.size() ; i++){
if (grumpy[i] == 0){
sum += customers[i];
}
}
while(j < grumpy.size()){
if(grumpy[j] == 1){
sum += customers[j];
}
if (j - i + 1 < minutes){
j++;
}
else if(j - i + 1 == minutes){
maxsum = max(sum, maxsum);
if (grumpy[i] == 1){
sum -= customers[i];
}
i++;
j++;
}
}
return maxsum;
}
};

subratbera
Автор

there is one more solution type
hear me out

so we take a sum of min satisfied that is initially 10
then we take a window of size 3
then we take an temp max_satisfied and change the all 1 s in the window to 0 ans sum it to 10
then slide the window by one and again change the 1 s to 0 and sum it to 10 it if its bigger than previous make it temp or move the window again
after ending you will find max satisfied 16

IndrajitBarman-cn
Автор

This code is written by me
could you please tell me what is the time complexity of this code:

class Solution {
public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
int ans = 0;
int sum = 0;
for(int i = 0; i < customers.length; i++){
if(grumpy[i] == 1){
int j = i; int x = 0;
int s = 0;
while(j < grumpy.length && x < minutes){
if(grumpy[j] == 1){
s += customers[j];
}
j++; x++;
}
sum = Math.max(sum, s);
}
else{
ans += customers[i];
}
}
return ans+sum;
}
}

animeworld