Skip to content

Commit 7ae6166

Browse files
solves maximum number of balls in a box
1 parent fbc9cc2 commit 7ae6166

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,7 @@
426426
| 1725 | [Number Of Rectangles That Can Form The Largest Square](https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square) | [![Java](assets/java.png)](src/NumberOfRectanglesThatCanFormTheLargestSquare.java) | |
427427
| 1732 | [Find the Highest Altitude](https://leetcode.com/problems/find-the-highest-altitude) | [![Java](assets/java.png)](src/FindTheHighestAltitude.java) | |
428428
| 1736 | [Latest Time by Replacing Hidden Digits](https://leetcode.com/problems/latest-time-by-replacing-hidden-digits) | [![Java](assets/java.png)](src/LatestTimeByReplacingHiddenDigits.java) | |
429-
| 1742 | [Maximum Number of Balls in a Box](https://leetcode.com/problems/maximum-number-of-balls-in-a-box) | | |
429+
| 1742 | [Maximum Number of Balls in a Box](https://leetcode.com/problems/maximum-number-of-balls-in-a-box) | [![Java](assets/java.png)](src/MaximumNumberOfBallsInABox.java) | |
430430
| 1748 | [Sum of Unique Elements](https://leetcode.com/problems/sum-of-unique-elements) | | |
431431
| 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated) | | |
432432
| 1758 | [Minimum Changes To Make Alternating Binary String](https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string) | | |

Diff for: src/MaximumNumberOfBallsInABox.java

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class MaximumNumberOfBallsInABox {
5+
public int countBalls(int lowLimit, int highLimit) {
6+
final Map<Integer, Integer> boxes = new HashMap<>();
7+
for (int ball = lowLimit ; ball <= highLimit ; ball++) {
8+
int boxNumber = sumOfDigits(ball);
9+
boxes.put(boxNumber, boxes.getOrDefault(boxNumber, 0) + 1);
10+
}
11+
return boxes.values().stream().max(Integer::compareTo).get();
12+
}
13+
14+
private int sumOfDigits(int n) {
15+
int sum = 0;
16+
while (n > 0) {
17+
sum += n % 10;
18+
n /= 10;
19+
}
20+
return sum;
21+
}
22+
}

0 commit comments

Comments
 (0)