code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

01 Subset Sum

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const subsetSum = (nums, target) => {
  const dfs = (index, currSum) => {
    if (index <= 0 || currSum <= 0) {
      return 0
    }
    if (nums[index] <= currSum) {
      return Math.max(nums[index] + dfs(index - 1, currSum - nums[index]), dfs(index - 1, currSum))
    } else {
      return dfs(index - 1, currSum)
    }
  }

  return dfs(nums.length - 1, target)
}

console.log(subsetSum([2, 3, 7, 8, 10], 11))

Created 2022-03-26T16:45:06+00:00 · Edit