class Solution {
int maxSum = Integer. MIN_VALUE;
public int maxPathSum ( TreeNode root) {
maxGain ( root) ;
return maxSum;
}
public int maxGain ( TreeNode node) {
if ( node == null) {
return 0 ;
}
int leftGain = Math. max ( maxGain ( node. left) , 0 ) ;
int rightGain = Math. max ( maxGain ( node. right) , 0 ) ;
int priceNewpath = node. val + leftGain + rightGain;
maxSum = Math. max ( maxSum, priceNewpath) ;
return node. val + Math. max ( leftGain, rightGain) ;
}
}
class Solution {
public int maxProfit ( int [ ] prices) {
int n = prices. length;
int [ ] [ ] dp = new int [ n] [ 2 ] ;
dp[ 0 ] [ 0 ] = 0 ;
dp[ 0 ] [ 1 ] = - prices[ 0 ] ;
for ( int i = 1 ; i < n; ++ i) {
dp[ i] [ 0 ] = Math. max ( dp[ i - 1 ] [ 0 ] , dp[ i - 1 ] [ 1 ] + prices[ i] ) ;
dp[ i] [ 1 ] = Math. max ( dp[ i - 1 ] [ 1 ] , dp[ i - 1 ] [ 0 ] - prices[ i] ) ;
}
return dp[ n - 1 ] [ 0 ] ;
}
}
class Solution {
public int maxProfit ( int [ ] prices) {
if ( prices. length == 0 )
return 0 ;
int max = 0 ;
int low = prices[ 0 ] ;
for ( int i = 1 ; i < prices. length; i++ )
{
if ( ( prices[ i] - low) > max)
{
max = prices[ i] - low;
}
if ( prices[ i] < low)
{
low = prices[ i] ;
}
}
return max;
}
}