diff options
Diffstat (limited to 'min_num_ops_ball_box.c')
-rw-r--r-- | min_num_ops_ball_box.c | 38 |
1 files changed, 26 insertions, 12 deletions
diff --git a/min_num_ops_ball_box.c b/min_num_ops_ball_box.c index a6cba59..1492a6e 100644 --- a/min_num_ops_ball_box.c +++ b/min_num_ops_ball_box.c @@ -1,25 +1,39 @@ // 1769. Minimum Number of Operations to Move All Balls to Each Box -#include <stdio.h> -#include <stdlib.h> -#include <string.h> +#include "leetcode.h" + +/* + * you have 'n' boxes. you are given a binary string 'boxes' of length 'n' where + * 'boxes[i]' is '0' if the i'th box is empty, and '1' if it contains one ball. + * in one operation, you can move one ball from a box to an adjacent box. box + * 'i' is adjacent to box 'j' if 'abs(i - j) == 1'. note that after doing so, + * there may be more than one ball in some boxes. return an array 'answer' of + * size 'n' where 'answer[i]' is the minimum number of operations needed to move + * all the balls to i'th box. + */ int *minOperations(char *boxes, int *returnSize) { - int len = strlen(boxes), steps; - int *ans = malloc(len * sizeof(int)); - for (int i = 0; i < len; i++) { + int n = strlen(boxes), steps; + int *ans = (int *)malloc(n * sizeof(int)); + for (int i = 0; i < n; i++) { steps = 0; - for (int j = 0; j < len; j++) + for (int j = 0; j < n; j++) if (boxes[j] == '1') steps += abs(i - j); ans[i] = steps; } - *returnSize = len; + *returnSize = n; return ans; } int main() { - char boxes1[] = {"110"}, boxes2[] = {"001011"}; - int rs1[] = {3}, rs2[] = {6}; - printf("%c\n", *minOperations(boxes1, rs1)); // expect: 1,1,3 - printf("%c\n", *minOperations(boxes2, rs2)); // expect: 11,8,5,4,3,4 + char *b1 = "110", *b2 = "001011"; + int rs1, *mo1 = minOperations(b1, &rs1); + int rs2, *mo2 = minOperations(b2, &rs2); + for (int i = 0; i < rs1; i++) + printf("%d ", mo1[i]); // expect: 1 1 3 + printf("\n"); + for (int i = 0; i < rs2; i++) + printf("%d ", mo2[i]); // expect: 11 8 5 4 3 4 + printf("\n"); + free(mo1), free(mo2); } |