본문 바로가기

Programming

[LeetCode] 1742. Maximum Number of Balls in a Box (TDD, 코테, 릿코드, tech interview)

TDD로 알고리즘 풀이 후 리팩토링

리팩토링해서 함수만들고 하면 성능이 좀 떨어짐

 

 

테스트코드

package algorithm_sites.leetcode;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

public class LeetCode_1742_MaximumNumberOfBallsInABoxTest {

    private LeetCode_1742_MaximumNumberOfBallsInABox test = new LeetCode_1742_MaximumNumberOfBallsInABox();

    @Test
    public void countBallsTest() {
        Assertions.assertThat(test.countBalls(1, 10)).isEqualTo(2);
        Assertions.assertThat(test.countBalls(5, 15)).isEqualTo(2);
        Assertions.assertThat(test.countBalls(19, 28)).isEqualTo(2);
    }

    @Test
    public void digitSumTest() {
        Assertions.assertThat(test.digitSum(12)).isEqualTo(3);
        Assertions.assertThat(test.digitSum(312)).isEqualTo(6);
        Assertions.assertThat(test.digitSum(4572)).isEqualTo(18);
        Assertions.assertThat(test.digitSum(9380)).isEqualTo(20);
        Assertions.assertThat(test.digitSum(0)).isEqualTo(0);
        Assertions.assertThat(test.digitSum(1)).isEqualTo(1);
        Assertions.assertThat(test.digitSum(990)).isEqualTo(18);
    }

}

 

풀이코드

package algorithm_sites.leetcode;

/**
 * Written by Gin (thesockerr@gmail.com) on 2021/12/11.
 */
public class LeetCode_1742_MaximumNumberOfBallsInABox {
    int[] boxes = new int[10 * 100000];

    // Process
    // 1. Input low high limits
    // 2. Iterate low to high (num)
    //  2.1. Get digitSum of num
    //  2.2. Put digitSum in boxNumber
    // 3. Get maxBoxNumber
    // 4. Return
    public int countBalls(int lowLimit, int highLimit) {
        // 2.
        fillTheBoxes(lowLimit, highLimit);

        // 3. / 4.
        return findMaxNumberOfMaxCountBox();
    }

    private void fillTheBoxes(int lowLimit, int highLimit) {
        for (int i = lowLimit; i <= highLimit; ++i) {
            ++boxes[digitSum(i)];
        }
    }

    private int findMaxNumberOfMaxCountBox() {
        int max = 0;
        for (int i = 0; i < boxes.length; ++i) {
            if (max < boxes[i]) {
                max = boxes[i];
            }
        }

        return max;
    }

    protected int digitSum(int number) {
        int sum = 0;

        while (number > 0) {
            sum += (number % 10);
            number /= 10;
        }

        return sum;
    }
}

 

 문제 영어 독해가 빡쎘음..