From 17b7131873dbbe1fdad26b750eeea14e6944f982 Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Sat, 21 Jan 2023 03:48:26 +0400 Subject: [PATCH] add leetcode Maximum Bags With Full Capacity of Rocks (#1196) * add leetcode Maximum Bags With Full Capacity of Rocks * Update leetcode/src/2279.c Co-authored-by: David Leal * Update leetcode/src/2279.c Co-authored-by: David Leal * Update leetcode/src/2279.c Co-authored-by: David Leal --- leetcode/DIRECTORY.md | 1 + leetcode/src/2279.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 leetcode/src/2279.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 0918a623..f37d64fc 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -129,6 +129,7 @@ | 2222 | [Number of Ways to Select Buildings](https://leetcode.com/problems/number-of-ways-to-select-buildings/) | [C](./src/2222.c) | Medium | | 2256 | [Minimum Average Difference](https://leetcode.com/problems/minimum-average-difference/) | [C](./src/2256.c) | Medium | | 2270 | [Number of Ways to Split Array](https://leetcode.com/problems/number-of-ways-to-split-array/) | [C](./src/2270.c) | Medium | +| 2279 | [Maximum Bags With Full Capacity of Rocks](https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/) | [C](./src/2279.c) | Medium | | 2304 | [Minimum Path Cost in a Grid](https://leetcode.com/problems/minimum-path-cost-in-a-grid/) | [C](./src/2304.c) | Medium | | 2482 | [Difference Between Ones and Zeros in Row and Column](https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column/description/) | [C](./src/2482.c) | Medium | | 2501 | [Longest Square Streak in an Array](https://leetcode.com/problems/longest-square-streak-in-an-array/description/) | [C](./src/2501.c) | Medium | diff --git a/leetcode/src/2279.c b/leetcode/src/2279.c new file mode 100644 index 00000000..8dc05d98 --- /dev/null +++ b/leetcode/src/2279.c @@ -0,0 +1,29 @@ +int compare(const int* i, const int* j) +{ + return *i - *j; +} + +// Sorting. +// Runtime: O(n*log(n)) +// Space: O(n) +int maximumBags(int* capacity, int capacitySize, int* rocks, int rocksSize, int additionalRocks) { + int* capacityLeft = malloc(capacitySize * sizeof(int)); + for (int i = 0; i < capacitySize; i++) { + capacityLeft[i] = capacity[i] - rocks[i]; + } + + qsort(capacityLeft, capacitySize, sizeof (int), (int(*) (const void*, const void*)) compare); + + int bags = 0; + for (int i = 0; i < capacitySize; i++) { + if (additionalRocks < capacityLeft[i]){ + break; + } + + additionalRocks -= capacityLeft[i]; + bags++; + } + + free(capacityLeft); + return bags; +}