Skip to content

Instantly share code, notes, and snippets.

@buchgr
Created January 23, 2014 22:59
Show Gist options
  • Select an option

  • Save buchgr/8588539 to your computer and use it in GitHub Desktop.

Select an option

Save buchgr/8588539 to your computer and use it in GitHub Desktop.
static class Node
{
int val;
Node left;
Node right;
Node(int val, Node left, Node right)
{
this.val = val;
this.left = left;
this.right = right;
}
}
private static int maxSubseq(Node current, int runningSum)
{
if (current == null)
return runningSum;
int max = runningSum;
int leftMax = maxSubseq(current.left, Math.max(runningSum, 0) + current.val);
max = Math.max(max, leftMax);
int rightMax = maxSubseq(current.right, Math.max(runningSum, 0) + current.val);
max = Math.max(max, rightMax);
return max;
}
public static int maxSubseq(Node root)
{
if (root == null)
return 0;
return maxSubseq(root, Integer.MIN_VALUE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment