So I have a circular linked list with each Node given by:
1 2 3 4 5
|
struct Node
{
int val;
Node* Next;
};
|
I'm asked to write a program to find largest the sum of consecutive nodes in the list.
Example Input/Output:
Input: 5 9 -99 2
Output: 16 |
What I'm thinking about is using the Kadane's algorithm given here (changed it a bit to apply for linked list):
http://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane.27s_algorithm
First I check whether all nodes are negative numbers. If so, the answer would be the biggest negative node.
If not all nodes are negative numbers then I'll use Kadane's algorithm to find the maximum sum of nodes without "going around" the circle. In the example it would be 5+9=14. I call this result number A.
Then, I multiply each node by -1, use Kadane's algorithm again to get number B(this will get B=99 in the example). After that I'll take number C = (Sum of all nodes) + B (C=16 in the example).
The answer would now be max(A,C).
Please help and tell me if my solution is correct. Is there any better algorithms out there? (I'm not asking for the code, just the algorithm) Can I extend this problem to get the chosen nodes for the largest sum too?
Thank you for your time and patience.