You are the owner of a company that creates alloys using various types of metals. There are n different types of metals available, and you have access to k machines that can be used to create alloys.
Each machine requires a specific amount of each metal type to create an alloy. For the i-th machine to create an alloy, it needs composition[i][j] units of metal of type j.
Initially, you have stock[i] units of metal type i, and purchasing one unit of metal type i costs cost[i] coins.
Given integers n, k, budget, a 2D array composition, and arrays stock and cost, your goal is to maximize the number of alloys the company can create while staying within the budget of budget coins.
All alloys must be created with the same machine.
Return the maximum number of alloys that the company can create.
💡 Note:Machine 0 needs [1,1,1] per alloy: cost = 1×1 + 1×2 + 1×3 = 6 per alloy. With budget 15, we can make 15÷6 = 2 alloys. Machine 1 needs [1,1,2] per alloy: cost = 1×1 + 1×2 + 2×3 = 9 per alloy. With budget 15, we can make 15÷9 = 1 alloy. Maximum is 2.
💡 Note:Only machine 0: needs [2,1] per alloy. For 5 alloys need [10,5]. Have [1,1], need to buy [9,4]. Cost = 9×1 + 4×1 = 13 > 10. For 4 alloys need [8,4], buy [7,3]. Cost = 7×1 + 3×1 = 10 ≤ 10. So maximum is 4 alloys.
The key insight is that for each machine, the number of affordable alloys increases monotonically with budget, making binary search applicable. Best approach uses binary search on the answer for each machine to find maximum alloys efficiently. Time: O(k × n × log(budget)), Space: O(1)
Common Approaches
✓
Bit Manipulation
⏱️ Time: N/A
Space: N/A
Backtracking
⏱️ Time: N/A
Space: N/A
Binary Search on Answer
⏱️ Time: O(k × n × log(budget))
Space: O(1)
For each machine, use binary search to find the maximum number of alloys we can make. The key insight is that if we can make X alloys, we can also make any number less than X, making this monotonic.
Brute Force with Linear Search
⏱️ Time: O(k × budget)
Space: O(1)
For each machine, incrementally try making 1, 2, 3... alloys until the budget is exceeded. Calculate the cost needed for each attempt and track the maximum achievable.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int maxNumberOfAlloys(int n, int k, int budget, int** composition, int* stock, int* cost) {
int maxAlloys = 0;
// Try each machine
for (int machine = 0; machine < k; machine++) {
// Binary search on number of alloys
int left = 0, right = 200000000; // Upper bound based on constraints
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if we can make mid alloys with this machine
long long totalCost = 0;
int canMake = 1;
for (int metal = 0; metal < n; metal++) {
long long needed = (long long)composition[machine][metal] * mid;
long long available = stock[metal];
if (needed > available) {
long long toBuy = needed - available;
totalCost += toBuy * cost[metal];
if (totalCost > budget) {
canMake = 0;
break;
}
}
}
if (canMake && totalCost <= budget) {
if (mid > maxAlloys) {
maxAlloys = mid;
}
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return maxAlloys;
}
int* parseArray(char* input, int* size) {
*size = 0;
// Handle empty array
if (strstr(input, "[]")) {
return NULL;
}
// Count elements
for (int i = 0; input[i]; i++) {
if (isdigit(input[i]) && (i == 0 || !isdigit(input[i-1]))) {
(*size)++;
}
}
if (*size == 0) return NULL;
int* result = (int*)malloc(*size * sizeof(int));
int idx = 0;
// Parse elements
for (int i = 0; input[i] && idx < *size; i++) {
if (isdigit(input[i]) || (input[i] == '-' && isdigit(input[i+1]))) {
char* endptr;
result[idx] = (int)strtol(&input[i], &endptr, 10);
idx++;
i = endptr - input - 1; // Move to end of number
}
}
return result;
}
int** parse2DArray(char* input, int* rows, int* cols) {
*rows = 0;
*cols = 0;
// Handle empty array
if (strstr(input, "[]")) {
return NULL;
}
// Count rows (inner arrays)
for (int i = 0; input[i]; i++) {
if (input[i] == '[' && i > 0) {
(*rows)++;
}
}
if (*rows == 0) return NULL;
// Find columns by parsing first row
int inFirstRow = 0;
for (int i = 1; input[i]; i++) {
if (input[i] == '[') {
inFirstRow = 1;
} else if (input[i] == ']' && inFirstRow) {
break;
} else if (inFirstRow && (isdigit(input[i]) || (input[i] == '-' && isdigit(input[i+1])))) {
(*cols)++;
// Skip rest of this number
if (input[i] == '-') i++;
while (input[i+1] && isdigit(input[i+1])) i++;
}
}
// Allocate matrix
int** matrix = (int**)malloc(*rows * sizeof(int*));
for (int i = 0; i < *rows; i++) {
matrix[i] = (int*)malloc(*cols * sizeof(int));
}
// Parse matrix
int row = 0, col = 0;
int inRow = 0;
for (int i = 1; input[i] && row < *rows; i++) {
if (input[i] == '[') {
inRow = 1;
col = 0;
} else if (input[i] == ']' && inRow) {
row++;
inRow = 0;
} else if (inRow && (isdigit(input[i]) || (input[i] == '-' && isdigit(input[i+1])))) {
char* endptr;
matrix[row][col] = (int)strtol(&input[i], &endptr, 10);
col++;
i = endptr - input - 1; // Move to end of number
}
}
return matrix;
}
int main() {
char input[10000];
// Read n
fgets(input, sizeof(input), stdin);
int n = atoi(input);
// Read k
fgets(input, sizeof(input), stdin);
int k = atoi(input);
// Read budget
fgets(input, sizeof(input), stdin);
int budget = atoi(input);
// Read composition
fgets(input, sizeof(input), stdin);
int rows, cols;
int** composition = parse2DArray(input, &rows, &cols);
// Read stock
fgets(input, sizeof(input), stdin);
int stockSize;
int* stock = parseArray(input, &stockSize);
// Read cost
fgets(input, sizeof(input), stdin);
int costSize;
int* cost = parseArray(input, &costSize);
int result = maxNumberOfAlloys(n, k, budget, composition, stock, cost);
printf("%d\n", result);
// Cleanup
if (composition) {
for (int i = 0; i < rows; i++) {
free(composition[i]);
}
free(composition);
}
if (stock) free(stock);
if (cost) free(cost);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
18.5K Views
MediumFrequency
~25 minAvg. Time
850 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.