arraysalgorithmkadanes-algorithm

Maximum subarray sum with same starting and end element


I got an online test problem where they gave a string of characters and a value for each character. Value of each character is in range [-10, 10]. The problem was to find a substring that starts and ends with same character and has maximum value. The problem easily reduces to a extended version of maximum subarray sum problem after replacing the characters with values. The constraint is the starting and ending values will be same. I came up with a naive solution and was not good enough. Can anyone tell me how to work this out with Kadane's algorithm or any other with a better time complexity?


Solution

  • This question is designed to make Kadane's algorithm a bad fit.

    You can still do it quickly and easily, though: