I know kdane algo but how to solve this
I’m unable to find out when to break out of loop
How to approach this problem?
There can be two cases for the maximum sum:
- Case 1: The elements that contribute to the maximum sum are arranged such that no wrapping is there. Examples: {-10, 2, -1, 5}, {-2, 4, -1, 4, -1}. In this case, Kadane’s algorithm will produce the result.
- Case 2: The elements which contribute to the maximum sum are arranged such that wrapping is there. Examples: {10, -12, 11}, {12, -5, 4, -8, 11}. find out the sum of non-contributing elements and subtract this sum from the total sum. To find out the sum of non contributing, invert the sign of each element and then run Kadane’s algorithm.
Finally, we compare the sum obtained by both cases and return the maximum of the two sums.