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
✓
Backtracking
⏱️ Time: N/A
Space: N/A
Bit Manipulation
⏱️ 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>
static int** parseMatrix(char* input, int* rows) {
// Remove all spaces first
char cleaned[10000];
int cleanIdx = 0;
for (int i = 0; input[i]; i++) {
if (input[i] != ' ') {
cleaned[cleanIdx++] = input[i];
}
}
cleaned[cleanIdx] = '\0';
// Remove outer []
char inner[10000];
strcpy(inner, cleaned + 1);
inner[strlen(inner) - 1] = '\0';
// Count rows and parse
int** matrix = (int**)malloc(100 * sizeof(int*));
for (int i = 0; i < 100; i++) {
matrix[i] = (int*)malloc(100 * sizeof(int));
}
*rows = 0;
int depth = 0;
char current[1000];
int currentIdx = 0;
for (int i = 0; i <= strlen(inner); i++) {
char c = (i < strlen(inner)) ? inner[i] : '\0';
if (c == '[') {
depth++;
if (depth == 1) {
currentIdx = 0;
}
} else if (c == ']' || c == '\0') {
if (depth == 1 || c == '\0') {
current[currentIdx] = '\0';
// Parse current row
int col = 0;
char tempCurrent[1000];
strcpy(tempCurrent, current);
char* token = strtok(tempCurrent, ",");
while (token != NULL) {
matrix[*rows][col++] = atoi(token);
token = strtok(NULL, ",");
}
(*rows)++;
currentIdx = 0;
}
if (c == ']') depth--;
} else if (c == ',' && depth == 0) {
// Skip comma between rows
} else if (depth == 1) {
current[currentIdx++] = c;
}
if (c == '\0') break;
}
return matrix;
}
static int* parseArray(char* input, int* size) {
int* result = (int*)malloc(100 * sizeof(int));
*size = 0;
// Remove all spaces
char cleaned[1000];
int cleanIdx = 0;
for (int i = 0; input[i]; i++) {
if (input[i] != ' ') {
cleaned[cleanIdx++] = input[i];
}
}
cleaned[cleanIdx] = '\0';
// Remove outer []
char inner[1000];
strcpy(inner, cleaned + 1);
inner[strlen(inner) - 1] = '\0';
if (strlen(inner) == 0) return result;
char tempInner[1000];
strcpy(tempInner, inner);
char* token = strtok(tempInner, ",");
while (token != NULL) {
if (strlen(token) > 0) {
result[(*size)++] = atoi(token);
}
token = strtok(NULL, ",");
}
return result;
}
static int canMake(int alloys, int* composition, int* stock, int* cost, int n, long long budget) {
long long totalCost = 0;
for (int i = 0; i < n; i++) {
long long needed = (long long)alloys * composition[i];
long long available = stock[i];
if (needed > available) {
long long toBuy = needed - available;
totalCost += toBuy * cost[i];
if (totalCost > budget) {
return 0;
}
}
}
return totalCost <= budget;
}
static int maxAlloysForMachine(int* composition, int* stock, int* cost, int n, long long budget) {
int left = 0, right = 2000000;
int result = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (canMake(mid, composition, stock, cost, n, budget)) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
int main() {
char line[10000];
// Read n
fgets(line, sizeof(line), stdin);
int n = atoi(line);
// Read k
fgets(line, sizeof(line), stdin);
int k = atoi(line);
// Read budget
fgets(line, sizeof(line), stdin);
long long budget = atoll(line);
// Read composition
fgets(line, sizeof(line), stdin);
int rows;
int** composition = parseMatrix(line, &rows);
// Read stock
fgets(line, sizeof(line), stdin);
int stockSize;
int* stock = parseArray(line, &stockSize);
// Read cost
fgets(line, sizeof(line), stdin);
int costSize;
int* cost = parseArray(line, &costSize);
int maxAlloys = 0;
// Try each machine
for (int i = 0; i < k; i++) {
int alloys = maxAlloysForMachine(composition[i], stock, cost, n, budget);
if (alloys > maxAlloys) {
maxAlloys = alloys;
}
}
printf("%d\n", maxAlloys);
// Cleanup
for (int i = 0; i < 100; i++) {
free(composition[i]);
}
free(composition);
free(stock);
free(cost);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
⚡ Linearithmic
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.