| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.AppleRedistributionIntoBoxes; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class AppleRedistributionIntoBoxesGreedy : IAppleRedistributionIntoBoxes |
| | | 16 | | { |
| | | 17 | | private const int MaxSize = 50; |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n + m) |
| | | 21 | | /// Space complexity - O(1) |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="apples"></param> |
| | | 24 | | /// <param name="capacities"></param> |
| | | 25 | | /// <returns></returns> |
| | | 26 | | public int MinimumBoxes(int[] apples, int[] capacities) |
| | 2 | 27 | | { |
| | 2 | 28 | | var applesCount = 0; |
| | | 29 | | |
| | 16 | 30 | | for (var i = 0; i < apples.Length; i++) |
| | 6 | 31 | | { |
| | 6 | 32 | | var apple = apples[i]; |
| | | 33 | | |
| | 6 | 34 | | applesCount += apple; |
| | 6 | 35 | | } |
| | | 36 | | |
| | 2 | 37 | | Span<int> boxes = stackalloc int[MaxSize + 1]; |
| | | 38 | | |
| | 22 | 39 | | for (var i = 0; i < capacities.Length; i++) |
| | 9 | 40 | | { |
| | 9 | 41 | | var capacity = capacities[i]; |
| | | 42 | | |
| | 9 | 43 | | boxes[capacity]++; |
| | 9 | 44 | | } |
| | | 45 | | |
| | 2 | 46 | | var result = 0; |
| | | 47 | | |
| | 204 | 48 | | for (var i = boxes.Length - 1; i >= 0; i--) |
| | 101 | 49 | | { |
| | 101 | 50 | | if (applesCount == 0) |
| | 1 | 51 | | { |
| | 1 | 52 | | break; |
| | | 53 | | } |
| | | 54 | | |
| | 100 | 55 | | var box = boxes[i]; |
| | | 56 | | |
| | 106 | 57 | | while (box > 0 && applesCount > 0) |
| | 6 | 58 | | { |
| | 6 | 59 | | applesCount -= i; |
| | | 60 | | |
| | 6 | 61 | | box--; |
| | | 62 | | |
| | 6 | 63 | | result++; |
| | 6 | 64 | | } |
| | 100 | 65 | | } |
| | | 66 | | |
| | 2 | 67 | | return result; |
| | 2 | 68 | | } |
| | | 69 | | } |