I initially thought this problem would require fancy algorithms, but I ended up using what I consider the simplest approach.
Let me explain my thought process.
At first, I was a bit confused and naively thought: start enumerating from the first element of the array, and if a later element is different from the “first” element, stop and move to the next loop, then output the maximum sum.
Obviously that’s wrong! It should be: a later element must be different from ALL previous elements.
WA #1.
OK, this brute force approach did pass. Now, the problem says “characters” – if we’re talking about English letters including both upper and lower case, that’s 26*2. All ASCII characters would be 256. I allocated an array of 300, which should be enough.
The logic was correct but I still got WA #2. Why? Because the termination condition wasn’t explicit enough. If there are no repeating characters all the way to the end, my program would break.
WA #3 was because the program would crash when there’s only one element. Boundary conditions matter a lot for simple problems!
Finally it was pending for a while – I kept thinking it would time out, but it didn’t.
Yay!
Actually, the time complexity can be further optimized. If we start searching from position x, and elements at positions i and j are the same, the next search can start from i+1 instead of x+1. This would keep the time at linear scanning, though we’d need to store the indices of i and j.
| |