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>
int maxCovered = 0;
int countCovered(int** matrix, int m, int n, int* selected, int selectedSize) {
int covered = 0;
int colSet[20] = {0}; // Assuming max 20 columns
for (int i = 0; i < selectedSize; i++) {
colSet[selected[i]] = 1;
}
for (int i = 0; i < m; i++) {
int isCovered = 1;
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 1 && !colSet[j]) {
isCovered = 0;
break;
}
}
if (isCovered) covered++;
}
return covered;
}
void backtrack(int** matrix, int m, int n, int colIdx, int* selected, int selectedSize, int numSelect) {
if (selectedSize == numSelect) {
int covered = countCovered(matrix, m, n, selected, selectedSize);
if (covered > maxCovered) {
maxCovered = covered;
}
return;
}
if (colIdx >= n || selectedSize + (n - colIdx) < numSelect) {
return; // Pruning
}
// Include current column
selected[selectedSize] = colIdx;
backtrack(matrix, m, n, colIdx + 1, selected, selectedSize + 1, numSelect);
// Exclude current column
backtrack(matrix, m, n, colIdx + 1, selected, selectedSize, numSelect);
}
int solution(int** matrix, int m, int n, int numSelect) {
maxCovered = 0;
int selected[20]; // Assuming max 20 columns
backtrack(matrix, m, n, 0, selected, 0, numSelect);
return maxCovered;
}
int** parseMatrix(char* input, int* m, int* n) {
// Count rows first
*m = 0;
for (int i = 0; input[i]; i++) {
if (input[i] == '[' && i > 0) (*m)++;
}
// Find n by parsing first row
*n = 0;
int inFirstRow = 0;
for (int i = 1; input[i]; i++) {
if (input[i] == '[') {
inFirstRow = 1;
} else if (input[i] == ']') {
break;
} else if (inFirstRow && isdigit(input[i])) {
(*n)++;
while (input[i+1] && isdigit(input[i+1])) i++; // Skip multi-digit numbers
}
}
int** matrix = (int**)malloc(*m * sizeof(int*));
for (int i = 0; i < *m; i++) {
matrix[i] = (int*)malloc(*n * sizeof(int));
}
// Parse the matrix
int row = 0, col = 0;
int inRow = 0;
for (int i = 1; input[i]; i++) {
if (input[i] == '[') {
inRow = 1;
col = 0;
} else if (input[i] == ']') {
if (inRow) row++;
inRow = 0;
} else if (inRow && isdigit(input[i])) {
matrix[row][col] = input[i] - '0';
col++;
}
}
return matrix;
}
int main() {
char input[1000];
fgets(input, sizeof(input), stdin);
int m, n;
int** matrix = parseMatrix(input, &m, &n);
int numSelect;
scanf("%d", &numSelect);
printf("%d\n", solution(matrix, m, n, numSelect));
// Cleanup
for (int i = 0; i < m; i++) {
free(matrix[i]);
}
free(matrix);
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.