Funcia
Lv.2bitsetdpknapsack

Split Candy Bags Equally

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Two brothers received NN bags of candy; bag i holds nums[i] candies and bags cannot be opened.

Return true if all bags can be handed out so that both brothers get exactly the same number of candies, otherwise false.

Examples

numsresult
[1, 5, 11, 5]true
[1, 2, 3, 5]false
[3, 3, 3, 4, 5]true

Example 1 — [11] and [1, 5, 5] both hold 11 candies.

Example 2 — There are 11 candies in total, which cannot be split evenly.

Example 3 — [3, 3, 3] and [4, 5] both hold 9 candies.

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(nums: int[]) → bool

Constraints

  • 1≤N=1 \le N = nums.length ≤200\le 200
  • 1≤1 \le nums[i] ≤100\le 100

Expected complexity

Time
O(N * S)
Space
O(S)

Examples

numsExpected
[1,5,11,5]true
[1,2,3,5]false
[3,3,3,4,5]true

Hint

Hint

If the total SS is odd the answer is false; otherwise ask whether some subset sums to exactly S/2S/2. Trying every subset is 2N2^N. Keep can[s] ("sum s is reachable") and, for each bag x, update can[s] |= can[s - x] with s going downwards so a bag is used at most once: O(N⋅S)O(N \cdot S). A bitset (can |= can << x) processes many sums per machine word.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251000 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4013verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.