Similar Problems
Similar Problems not available
Maximize The Minimum Powered City - Leetcode Solution
Companies:
LeetCode: Maximize The Minimum Powered City Leetcode Solution
Difficulty: Hard
Topics: greedy binary-search sliding-window array prefix-sum
Problem Statement:
You are given n cities. You are given an array of integers p where the ith element denotes the population of the ith city. You need to distribute the population among these n cities such that the minimum powered city is maximum. A city is said to be powered if its population is at least equal to the minimum population among all the cities. Maximum of the minimum powered cities is to be maximized. Find the maximum value of minimum powered city possible.
Example:
Input: n = 3, p = [3, 6, 9] Output: 3
Input: n = 3, p = [4, 10, 12] Output: 4
Solution:
We need to find the maximum value of minimum powered city possible. Let's start by setting the minimum powered city as minimum population and maximum powered city as maximum population.
We can perform binary search for the answer. And use greedy approach for each guess in binary search.
Start with guessing the mid value between minimum and maximum powered cities. Let's call it as guess value (mid).
iterate from i = 1 to n cities:
- If the city i has population greater than or equal to mid, add it to the current group.
- if the sum of populations in this group becomes greater than or equal to mid, we need to switch to a new group.
Keep track of number of groups formed. If number of groups formed is greater than the given limit k, it means that mid value is selected too low, so we need to search for higher value for maximum powered city. So change the search range to [mid+1, max].
If number of groups formed is less than or equal to k, it means that mid value is selected high, so we need to search for lower value for maximum powered city. So change the search range to [min, mid].
At last, the minimum powered city would be equal to the maximum value of the group minimums. This would be the answer for this scenario.
Repeat the above process until minimum powered city becomes maximum powered city.
The time complexity of this algorithm is O(nlog(sum of population)).
Code:
int n, k; vector<int> p;
bool check(int mid) { int cnt = 1, sum = 0; for (int i = 0; i < n; i++) { if (p[i] > mid) return false; sum += p[i]; if (sum > mid) { sum = p[i]; cnt++; } } return cnt <= k; }
int solve() { int l = 0, r = accumulate(p.begin(), p.end(), 0); int ans = 0; while (l <= r) { int mid = (l + r) / 2; if (check(mid)) { ans = mid; r = mid - 1; } else { l = mid + 1; } } return ans; }
int main() { cin >> n >> k; p.resize(n); for (int i = 0; i < n; i++) { cin >> p[i]; } cout << solve() << endl; }
Maximize The Minimum Powered City Solution Code
1