From 794ec129aec8cf4e904041c88ef1d1d40d194958 Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Fri, 2 Dec 2022 09:03:24 +0400 Subject: [PATCH] feat: add Minimum Number of Operations to... (#1146) ...Move All Balls to Each Box LeetCode problem. * add Minimum Number of Operations to Move All Balls to Each Box leetcode * chore: apply suggestions from code review * Update leetcode/src/1769.c Co-authored-by: Taj Co-authored-by: David Leal Co-authored-by: Taj --- leetcode/DIRECTORY.md | 1 + leetcode/src/1769.c | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 leetcode/src/1769.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index da623564..73157c2b 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -100,6 +100,7 @@ | 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops/) | [C](./src/1184.c) | Easy | | 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [C](./src/1189.c) | Easy | | 1207 | [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C](./src/1207.c) | Easy | +| 1769 | [Minimum Number of Operations to Move All Balls to Each Box](https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/) | [C](./src/1769.c) | Medium | | 1524 | [Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/) | [C](./src/1524.c) | Medium | | 1653 | [Minimum Deletions to Make String Balanced](https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/) | [C](./src/1653.c) | Medium | | 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/) | [C](./src/1752.c) | Easy | diff --git a/leetcode/src/1769.c b/leetcode/src/1769.c new file mode 100644 index 00000000..e1a81d04 --- /dev/null +++ b/leetcode/src/1769.c @@ -0,0 +1,41 @@ +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ + +// Count one's from right. Each step from right side decrease for one for each 1's and increase from left: +// 1001*0101 -> left: 4 + 1, right: 2 + 4 +// 10010*101 -> left: (4+1) + (1+1), right: (2-1) + (4-1) +// Runtime: O(n) +// Space: O(1) +int* minOperations(char* boxes, int* returnSize){ + int leftOnes = 0; + int leftCommonDistance = 0; + + int rightOnes = 0; + int rightCommonDistance = 0; + + int boxesLength = strlen(boxes); + + *returnSize = boxesLength; + int* result = malloc(boxesLength * sizeof(int)); + + for (int i = 0; i < boxesLength; i++){ + if (boxes[i] == '1'){ + rightOnes += 1; + rightCommonDistance += i; + } + } + + for (int i = 0; i < boxesLength; i++){ + if (boxes[i] == '1'){ + rightOnes -= 1; + leftOnes += 1; + } + + result[i] = rightCommonDistance + leftCommonDistance; + rightCommonDistance -= rightOnes; + leftCommonDistance += leftOnes; + } + + return result; +}