[Algorithm] Largest sum of non-adjacent numbers

Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.

For example, [2, 4, 6, 2, 5] should return 13, since we pick 26, and 5[5, 1, 1, 5] should return 10, since we pick 5 and 5.

Follow-up: Can you do this in O(N) time and constant space

 

How to think?

Always start from make few assumption / examples to see the parttens:

For example:

[5,1,1,5]

Start from i = 0: max sum can be Math.max(5, 0)

// memo: [5]

Then i = 1: max sum can be Math.max(memo[0], arr[1]), which is memo[1] = Math.max(5, 1) ---> 5

// memo :: [5, 5]

Then i = 2: max sum can be Math.max(memo[i - 1], arr[i] + memo[i - 2]), which is memo[2] = Math.max(5, 1 +5) --> 6:

// memo :: [5, 5, 6]

Then i = 3, should follow i = 2 partten:

// memo :: [5, 5, 6, 10]

 

So now, we got our partten:

for i = 2 to length
    memo[i] = Math.max(memo[i - 1], memo[i - 2] + arr[i])

 

Code:

复制代码
function maxNonAdjSum(arr) {
  const memo = new Array(arr.length).fill(0);
  memo[0] = Math.max(0, arr[0]);
  memo[1] = Math.max(arr[1], memo[0]);

  for (let i = 2; i < arr.length; i++) {
    memo[i] = Math.max(memo[i-1], arr[i] + memo[i - 2]);
  }

  return memo;
}

console.log(maxNonAdjSum([2, 4, 6, 2, 5])); // 13
console.log(maxNonAdjSum([5, 1, 1, 5])); // 10 
console.log(maxNonAdjSum([2, 4, 6, 2, 5, -3, 4, 0])); // 17
复制代码

 

To improve it furuther for space, we don't really need to keep 'memo' as a whole array, we just need to remember 3 values:

// [max_inc, max_not_inc, max]

And:

max = Math.max(max + max_inc, max_not_inc)

 

Cdoe:

复制代码
function maxNonAdjSum2(arr) {
  let max_inc = Math.max(0, arr[0]);
  let max_not_inc = Math.max(arr[1], max_inc);

  let max = max_inc
  for (let i = 2; i < arr.length; i++) {
    max = Math.max(arr[i] + max_inc, max_not_inc);
    max_inc = max_not_inc;
    max_not_inc = max;
  }

  return max;
}

console.log(maxNonAdjSum2([2, 4, 6, 2, 5])); // 13
console.log(maxNonAdjSum2([5, 1, 1, 5])); // 10
console.log(maxNonAdjSum2([2, 4, 6, 2, 5, -3, 4, 0])); // 17
复制代码

 

posted @   Zhentiw  阅读(349)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-03-18 [Ramda] Get Deeply Nested Properties Safely with Ramda's path and pathOr Functions
2016-03-18 [Angular 2] Using events and refs
2016-03-18 [Angular 2] Writing a Simple Angular 2 Component
2016-03-18 [Angular 2] WebStorm - Managing Imports
点击右上角即可分享
微信分享提示