Skip to content

Instantly share code, notes, and snippets.

@HarshKumarChoudary
Created July 21, 2022 07:55
Show Gist options
  • Save HarshKumarChoudary/167dcc5469d711f484530a566657d797 to your computer and use it in GitHub Desktop.
Save HarshKumarChoudary/167dcc5469d711f484530a566657d797 to your computer and use it in GitHub Desktop.
Best Approach Code Although there is one approach with O(N) also
class Solution{
public:
int min_sprinklers(int gallery[], int n)
{
int ans = 0;
vector<pair<int,int>>v;
for(int i = 0; i < n; ++ i){
if(gallery[i] == -1)continue;
int left = max(0,i-gallery[i]);
int right = min(n-1,i+gallery[i]);
v.push_back({left,right});
}
sort(v.begin(),v.end());
if(v.size() == 0)return -1;
v.push_back({ INT_MAX, INT_MAX });
int st = 0;
int en = -1;
ans = 0;
int i = 0;
// for(auto a:v){
// cout<<a.first<<" "<<a.second<<endl;
// }
// if(st!=0)return -1;
while(i<v.size()){
if(v[i].first<=st){
en = max(en,v[i].second);
++i;
}else{
++ans;
st = en+1;
if(en >= n-1)break;
if(v[i].first>en+1){
break;
}
}
}
if(en<n-1)return -1;
return ans;
}
};
// Link:- https://practice.geeksforgeeks.org/problems/410d51d667ab93f2219b15126f001f32e8bb029e/1?page=1&difficulty[]=1&difficulty[]=2&status[]=unsolved&sortBy=submissions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment