# This code Passed in other Online Judge sites and eclipse BUT failed in Leetcode ? :O :O

• The following basic test case failed ,
In other Online Judge the solution is passed :O

Input: [-3]
Output: 1
Expected: -3

How the output 1 possible ?

//added the comment for this test case
enter code here

int MaxSoFar=INT_MIN;

int maxof(int a , int b){
return a>b?a:b;
}

int maxPathSum_Recursively(struct TreeNode* root) {

``````if(root==NULL)
return 0;

if(root){//post order traverse

int Lmax=maxPathSum_Recursively(root->left);//return 0
int Rmax=maxPathSum_Recursively(root->right); //return 0
int Smax=root->val;//-3
if(Lmax>0)
Smax=Smax+Lmax;
if(Rmax>0)
Smax=Smax+Rmax;

MaxSoFar=maxof(MaxSoFar,Smax);  //INTMIN,-3==>thus -3

return maxof(root->val ,maxof(Lmax+root->val, Rmax+root->val));

}
``````

}

int maxPathSum(struct TreeNode* root) {

``````maxPathSum_Recursively(root);
return MaxSoFar;
``````

}

• Maybe a bit late for this response, but stumbled on to this while looking for some info to solve a similar problem with my code.
I am no expert, however, may be resetting the global variable MaxSoFar; from within maxPathSum() could help.

``````int maxPathSum(struct TreeNode* root) {
MaxSoFar=INT_MIN;` // reset the global variable
maxPathSum_Recursively(root);
return MaxSoFar;
}
``````

I am basing this on the following FAQ at https://leetcode.com/faq/

Why does my code produce a different output compared to my local environment?

First of all, LeetCode Judger executes all test cases using the same program instance, which means you need to check the following:
Are there any global or static variables declared? Please avoid these variables if possible. If you must declare one, remember to reset them either in the default constructor or in the first line of your called method.

• Accepted solution is :

int maxof(int a , int b){

return a>b?a:b;

}

int maxPathSum_Recursively(struct TreeNode* root , int *MaxSoFar) {

``````if(root==NULL)
return 0;

int Lmax=maxPathSum_Recursively(root->left, MaxSoFar);
int Rmax=maxPathSum_Recursively(root->right , MaxSoFar);

int max_across_root=root->val;
if(Lmax>0)
max_across_root+=Lmax;
if(Rmax>0)
max_across_root+=Rmax;

if(max_across_root>*MaxSoFar)
*MaxSoFar=max_across_root;

return maxof(root->val  , maxof(Lmax,Rmax)+root->val);
``````

}

int maxPathSum(struct TreeNode* root) {

``````   int MaxSoFar=INT_MIN;
maxPathSum_Recursively(root, &MaxSoFar);
return MaxSoFar;
``````

}

• i modified my code , please check

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.