Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Solution For Aggresive Cows Problem in Cpp #341

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,5 @@
| parvez Mohammad|<a href="https://github.com/mdparvez6">mdparvez6</a>|
| Rakhi M Bhagwat |<a href="https://github.com/Rakhi-2002">Rakhi-2002</a>|
| Jobin Abraham | <a href="https://github.com/jobs-code">jobs-code</a> |
| Helen Sahith Sadhe |<a href="https://github.com/helensahith">helensahith</a>|
| Helen Sahith Sadhe |<a href="https://github.com/helensahith">helensahith</a>|
| Aman Srivastava |<a href="https://github.com/its-amans">its-amans</a>|
52 changes: 52 additions & 0 deletions c++/AggresiveCows.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// its-amans
// DSA
// 12/10/2024

//code studio problem link : https://www.naukri.com/code360/problems/aggressive-cows_1082559

bool possiblesolution(vector<int> &stalls, int n, int k, int mid){
int cowcount = 1; // Starting with 1 cow at the first stall
int lastpos = stalls[0]; // Position of the last placed cow

for(int i = 1; i < n; i++){ // Start from the second stall
if((stalls[i] - lastpos) >= mid){
cowcount++;
lastpos = stalls[i]; // Update the last cow's position
}
if(cowcount == k){ // If we've placed all cows
return true;
}
}
return false;
}

int aggressiveCows(vector<int> &stalls, int k) {
// Sort the stalls positions
sort(stalls.begin(), stalls.end());

int s = 0;
int max = stalls[stalls.size() - 1]; // Max stall position
int n = stalls.size();

// Limiting Case: if cows are more than stalls, return -1
if(n < k){
return -1;
}

int e = max;
int ans = -1;
int mid = s + (e - s) / 2;

// Binary search to find the largest minimum distance
while(s <= e){
if(possiblesolution(stalls, n, k, mid)){
ans = mid; // Possible solution found, try for larger distance
s = mid + 1;
} else {
e = mid - 1; // Try for smaller distance
}
mid = s + (e - s) / 2;
}

return ans;
}