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:
parent
8915c79d5f
commit
e4932de4b6
1 changed files with 26 additions and 0 deletions
26
kt/partition-equal-subset-sum.kt
Normal file
26
kt/partition-equal-subset-sum.kt
Normal 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]
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue