I want to know how to approach this question
Approach for the question
to solve this question use Kadane’s algorithm for circular array
Algorithm
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.
Reference Code
why did we reverse the signs of the elements?
yes reverse sign of every element
it is the part of algorithm
you have to follow this
basically is done to calculate the sum of non contributing elements
what are non contributing elements exactly?
those elements which are not contributing in normal kadane’s algorithms
okay, but the code you provided isn’t working
remove line no. 24 then it works
Removed, but still not working
what not working??
it is giving wrong ans or not passing testcases?
Giving wrong ans and not passing test cases as well
actually my code is for only one testcases
but in the question there are multiple testcase
so you need to adjust that
Modified Code
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.