Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens.
You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial.
A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following:
The number of complete gardens multiplied by full.
The minimum number of flowers in any of the incomplete gardens multiplied by partial. If there are no incomplete gardens, then this value will be 0.
Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
💡 Note:Optimal strategy: Make gardens complete by adding flowers: [6,6,1,6]. This gives us 3 complete gardens (beauty = 3×5 = 15) and 1 incomplete garden with minimum 1 flower (beauty = 1×3 = 3). Total beauty = 15 + 3 = 18. Actually, we can achieve 25 by making all gardens have at least 3 flowers: [3,3,3,3] using 4 flowers, then complete 2 gardens: [6,6,3,3] using 3 more flowers. Beauty = 2×5 + 3×3 = 19. Better: [1,6,6,6] uses 7 flowers exactly, giving 3×5 + 1×3 = 18. The optimal is [3,6,6,6] but this needs 8 flowers. Actually [2,6,6,6] needs 7 flowers and gives 3×5 + 2×3 = 21. Wait, let me recalculate: We can achieve [4,4,4,6] using 7 flowers, giving 1×5 + 4×3 = 17. Or [3,6,6,6] using 8 flowers. The maximum achievable is 25 with strategy [5,5,5,5] using 6 flowers for incomplete beauty 5×3=15, or other combinations.
💡 Note:We can make all gardens complete: [5,5,5,5] using newFlowers = (5-2)+(5-4)+(0)+(5-3) = 3+1+0+2 = 6 ≤ 10. Beauty = 4×2 + 0×6 = 8. Or keep some incomplete for higher partial value: make 3 complete [2,5,5,5] using 5 flowers, incomplete beauty = 2×6 = 12, total = 3×2 + 12 = 18. Better: make 2 complete [4,4,5,5] using 3 flowers, remaining 7 flowers can raise minimum to 4, beauty = 2×2 + 4×6 = 28. Even better: make 1 complete [5,5,5,3] using 4 flowers, remaining 6 can make minimum 5, but that makes all complete, so beauty = 4×2 = 8. Actually, optimal is making minimum 5 for incomplete: we can achieve [5,4,5,5] using 6 flowers with beauty = 3×2 + 4×6 = 30.
💡 Note:Since partial=5 is much higher than full=1, it's better to keep gardens incomplete. We can distribute 4 newFlowers evenly to get [2,2,2,2]. Beauty = 0×1 + 2×5 = 10. Or we could make [5,1,1,1] to get beauty = 0×1 + 1×5 = 5. The optimal distribution is [2,2,2,2] giving beauty = 4×5 = 20 (all incomplete with minimum 2).
The key insight is to balance between making gardens complete (earning full points each) versus maximizing the minimum incomplete garden value (earning partial points). Best approach is Binary Search + Enumeration: sort gardens, enumerate complete garden counts, and binary search optimal minimum for incomplete gardens. Time: O(n² log n), Space: O(n)
Common Approaches
✓
Binary Search on Answer + Greedy
⏱️ Time: O(n² log n)
Space: O(n)
Sort gardens and for each possible number of complete gardens (0 to n), use binary search to find the maximum achievable minimum value for incomplete gardens. Greedily make the largest gardens complete first.
Brute Force - Try All Distributions
⏱️ Time: O(n^newFlowers)
Space: O(1)
Generate all possible ways to distribute newFlowers among the gardens, calculate beauty for each distribution, and return the maximum. This involves trying every combination of flower assignments.
Greedy with Prefix Sum Optimization
⏱️ Time: O(n²)
Space: O(n)
Sort gardens, then use prefix sums to quickly calculate the cost of achieving different minimum values for incomplete gardens. For each number of complete gardens, greedily find the best minimum value.
Binary Search on Answer + Greedy — Algorithm Steps
Step 1: Sort gardens in descending order to prioritize largest gardens
Step 2: For each possible number of complete gardens (0 to n)
Step 3: Calculate cost to make that many gardens complete
Step 4: Binary search on remaining flowers to maximize minimum incomplete garden
Step 5: Return maximum beauty across all possibilities
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Sort Gardens
Sort to prioritize making largest gardens complete
2
Enumerate Complete
Try 0,1,2...n complete gardens
3
Binary Search
For remaining flowers, find max achievable minimum for incomplete gardens
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int flowers[100000];
static int incompleteFlowers[100000];
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
long long solution(int* flowers, int n, int newFlowers, int target, int full, int partial) {
qsort(flowers, n, sizeof(int), compare);
// Remove gardens that are already complete
int incompleteCount = 0;
int alreadyComplete = 0;
for (int i = 0; i < n; i++) {
if (flowers[i] < target) {
incompleteFlowers[incompleteCount++] = flowers[i];
} else {
alreadyComplete++;
}
}
if (incompleteCount == 0) {
// All gardens are already complete
return (long long) alreadyComplete * full;
}
long long maxBeauty = 0;
// Try each number of additional complete gardens from incomplete ones
for (int additionalComplete = 0; additionalComplete <= incompleteCount; additionalComplete++) {
int totalComplete = alreadyComplete + additionalComplete;
int remainingIncomplete = incompleteCount - additionalComplete;
// Cost to make 'additionalComplete' gardens complete (largest incomplete ones)
long long completeCost = 0;
for (int i = incompleteCount - additionalComplete; i < incompleteCount; i++) {
completeCost += target - incompleteFlowers[i];
}
if (completeCost > newFlowers) {
continue;
}
long long remaining = newFlowers - completeCost;
long long beauty;
if (remainingIncomplete == 0) {
beauty = (long long) totalComplete * full;
} else {
// Binary search on minimum value for remaining incomplete gardens
int left = incompleteFlowers[0], right = target - 1;
int bestMin = incompleteFlowers[0];
while (left <= right) {
int mid = (left + right) / 2;
long long cost = 0;
for (int i = 0; i < remainingIncomplete; i++) {
if (incompleteFlowers[i] < mid) {
cost += mid - incompleteFlowers[i];
}
}
if (cost <= remaining) {
bestMin = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
beauty = (long long) totalComplete * full + (long long) bestMin * partial;
}
if (beauty > maxBeauty) {
maxBeauty = beauty;
}
}
return maxBeauty;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
char line[1000];
fgets(line, sizeof(line), stdin);
// Parse array
int n;
parseArray(line, flowers, &n);
int newFlowers, target, full, partial;
scanf("%d", &newFlowers);
scanf("%d", &target);
scanf("%d", &full);
scanf("%d", &partial);
printf("%lld\n", solution(flowers, n, newFlowers, target, full, partial));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n² log n)
Sort O(n log n), enumerate n complete garden counts, each with binary search O(n log n)
n
2n
⚠ Quadratic Growth
Space Complexity
O(n)
Extra array for sorted gardens and prefix sums
n
2n
⚡ Linearithmic Space
28.5K Views
MediumFrequency
~35 minAvg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.