I want to find the maximum sum of the given values in a given range, and the values chosen has to be contiguous and in complexity of O(logn) while calculating the sum.
For example the input values are: 1 2 -100 3 4
and I want the maximum value from index 1 to 3 (index starts from 1), then the output will be:3
because 1+2=3.
I know this question has been solved in a way using the array, you can look up in here
Now I have to complete it in complexity of O(logn)... What I can only think of is to build an AVL tree to save the values. But I don't exactly know how to find the max sum, since it has also to be contiguous. Does anyone have some ideas?
By using this I could find an max sum but not contiguous. I tried to fix it to satisfy that condition but I still can't.
btw my structure for the AVL tree is:
struct Node{
int data;
int height; //used to build AVL tree
int index; //save the sequence of the input
struct Node* left;
struct Node* right;
}
int findMaxSum(struct Node* root, int x, int y) //my function to find max sum (x y are my range index, from x to y)
{
int Max, returnMax;
if (root==NULL){
return 0;
}
int left= findMaxSum(root->left, x, y);
int right= findMaxSum(root->right, x, y);
if (root->index>=x && root->index<=y && (preIndex==x || (root->index-1==preIndex))){
//preIndex is a global var to save the previous index
returnMax= max((max(left, right)+root->key), root->key);
Max= max(returnMax, (left+right+root->key));
if (Max>maxSum){
maxSum= Max;
preIndex=root->index;
}
}
else returnMax=root->key;
return returnMax;
}
My actual input is to read some integers from the txt file:8
-4990 -9230 -3269 -2047 2875 3955 6022 8768
1 4
(8
means there will be 8 numbers to participate the calculation. 1 4
means to choose the max sum between -4990 -9230 -3269 -2047
since index starts from 1).
My wrong output is: 1908
and the answer should be -2047
.
I think the problem of my code is that when I use recursive, my sum will accumulate the sums of every node(even the nodes that I don't want to count).
Is there another way of solving this or can it be fixed by adding conditions?