You are given an integer array apples
of length n
, where apples[i]
represents the number of apples in the i-th
box.
Your goal is to make all the boxes have the same number of apples by performing the following operations any number of times:
Return true
if you can achieve this goal, and false
otherwise.
Example 1:
Input: apples = [2, 5, 3, 9]
Output: False
Explanation: It is not possible to make all the boxes have the same number of apples.
Example 2:
Input: apples = [3, 3, 3]
Output: True
Explanation: All boxes already contain the same number of apples.
apples
array?To simplify, let’s assume:
To solve this problem, consider the following steps:
n
.false
since we cannot evenly distribute apples into each box.n
, it means we can evenly distribute them. (Total sum modulo the number of boxes should equal 0).Here’s a Python function to implement the aforementioned strategy:
def canRedistributeApples(apples):
total_apples = sum(apples)
n = len(apples)
# Check if the total number of apples is divisible by the number of boxes
if total_apples % n == 0:
return True
else:
return False
# Test case
print(canRedistributeApples([2, 5, 3, 9])) # Output: False
print(canRedistributeApples([3, 3, 3])) # Output: True
sum(apples)
.n
, using len(apples)
.total_apples
is divisible by n
.true
if divisible, otherwise false
.This algorithm runs in O(n) time where n
is the length of the input list apples
, which is efficient for the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?