kt: add «416. Partition Equal Subset Sum»

URL:	https://leetcode.com/problems/partition-equal-subset-sum/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-04-07 12:20:00 +02:00
parent 8915c79d5f
commit e4932de4b6
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,26 @@
class Solution {
fun canPartition(nums: IntArray): Boolean {
val total = nums.sum()
if (total % 2 != 0) {
return false
}
val target = total / 2
val dp = BooleanArray(target + 1)
dp[0] = true
for (num in nums) {
var current = target
while (current >= num) {
dp[current] = dp[current] || dp[current - num]
if (dp[target]) {
return true
}
current--
}
}
return dp[target]
}
}