[Algorithm] DP - 03. Max Subset Sum No Adjacent - Slice window

Write a function that takes in an array of positive integers and returns the maximum sum of non-adjacent elements in the array.

If the input array is empty, the function should return 0.

Sample Input

array = [75, 105, 120, 75, 90, 135]

Sample Output

330 // 75 + 120 + 135
 
 
Normal approach:
// Time: O(N)
// Space: O(N)
function maxSubsetSumNoAdjacent(array) {
  if (array.length === 0) {
    return 0
  }

  const dp = Array.from(array, (val, i) => {
    if (i === 0) {
      return val
    } else if (i === 1) {
      return Math.max(array[0], array[1])
    } else {
      return 0
    }
  })

  for (let i = 2; i < array.length; i++) {
    if (dp[i-2] + array[i] > dp[i-1]) {
      dp[i] = dp[i-2] + array[i] 
    } else {
      dp[i] = dp[i-1]
    }
  }

  return dp[dp.length - 1]
}

// Do not edit the line below.
exports.maxSubsetSumNoAdjacent = maxSubsetSumNoAdjacent;

 

It can be improved to: 

// Time: O(N)
// Space: O(1)

 

We don't need to track the whole dp array, and loop from beginning to current i position to get max sum.

 

What we can do for this task is that we only need to keep tracking two values, a samll slice window.

if ary[i] + dp[0] > dp[1]
  dp[0] = dp[1]
  dp[1] = ary[i] + dp[0]
else
  dp[0] = dp[1]
function maxSubsetSumNoAdjacent(array) {
  if (array.length === 0) {
    return 0
  }

  const dp = [0, 0]
  
  for (let i = 0; i < array.length; i++) {
    if (dp[0] + array[i] > dp[1]) {
      const val = dp[0] + array[i]
      dp[0] = dp[1]
      dp[1] = val
    } else {
      dp[0] = dp[1]
    }
  }

  return dp[1]
}

// Do not edit the line below.
exports.maxSubsetSumNoAdjacent = maxSubsetSumNoAdjacent;

 

posted @   Zhentiw  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-04-05 [Javascript] Data ownership, avoid accidently mutation
2019-04-05 [Jade] Piped text
2019-04-05 [Docker] Driver Bridge network for linking containers
2019-04-05 [Spring Boot] Complex Scope Scenarios of a Spring Bean - Mix Prototype and Singleton, ScopeProxy
2019-04-05 [Spring Boot] Singleton and Prototype
2018-04-05 [React Router] Prevent Navigation with the React Router Prompt Component
2018-04-05 [Web Worker] Introduce to Web Worker
点击右上角即可分享
微信分享提示