Skip to content

Instantly share code, notes, and snippets.

@karenpeng
Created January 29, 2016 08:51
Show Gist options
  • Save karenpeng/40aced651b9611ec9858 to your computer and use it in GitHub Desktop.
Save karenpeng/40aced651b9611ec9858 to your computer and use it in GitHub Desktop.
var assert = require('assert')
function maxSumIncrease(arr){
if(arr.length === 0) return 0
var max = arr[0]
var sum = arr[0]
for(var i = 1; i < arr.length; i++){
if(arr[i] === arr[i - 1] + 1){
sum += arr[i]
}
else{
sum = arr[i]
}
max = Math.max(sum, max)
}
return max
}
assert.equal(maxSumIncrease([1,2,3,0,4,0,5,6]), 11)
assert.equal(maxSumIncrease([]), 0)
assert.equal(maxSumIncrease([-1]), -1)
assert.equal(maxSumIncrease([-1, 0, 1, 0, 2]), 2)
function Node(val){
this.val = val
this.left = null
this.right = null
}
var a = new Node(1)
var b = new Node(2)
var c = new Node(3)
var d = new Node(0)
var e = new Node(4)
var f = new Node(0)
var g = new Node(5)
var h = new Node(6)
var x = new Node(7)
var z = new Node(9)
a.left = b
a.right = d
b.left = c
b.right = h
d.right = e
e.right = g
g.left = x
g.right = z
function maxSumIncreaseTree(root){
if(root === null) return 0
return helper(root, -Infinity, 0, root.val - 1)
}
function helper(root, max, sum, pre){
if(root === null) return max
if(root.val === pre + 1){
sum += root.val
}else{
sum = root.val
}
max = Math.max(max, sum)
var l = helper(root.left, max, sum, root.val)
var r = helper(root.right, max, sum, root.val)
return Math.max(l, r)
}
assert.equal(maxSumIncreaseTree(a), 9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment