- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 54 lines of Java from the credited upstream file 1960.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public long maxProduct(String s) {3 final int n = s.length();4 long ans = 1;5 6 int[] maxLeft = manacher(s, n);7 8 int[] maxRight = manacher(new StringBuilder(s).reverse().toString(), n);9 10 reverse(maxRight, 0, n - 1);11 12 for (int i = 1; i < n; ++i)13 ans = Math.max(ans, (long) maxLeft[i - 1] * maxRight[i]);14 15 return ans;16 }17 18 private int[] manacher(final String s, int n) {19 int[] maxExtends = new int[n];20 int[] leftToRight = new int[n];21 Arrays.fill(leftToRight, 1);22 int center = 0;23 24 for (int i = 0; i < n; ++i) {25 final int r = center + maxExtends[center] - 1;26 final int mirrorIndex = center - (i - center);27 int extend = i > r ? 1 : Math.min(maxExtends[mirrorIndex], r - i + 1);28 while (i - extend >= 0 && i + extend < n && s.charAt(i - extend) == s.charAt(i + extend)) {29 leftToRight[i + extend] = 2 * extend + 1;30 ++extend;31 }32 maxExtends[i] = extend;33 if (i + maxExtends[i] >= r)34 center = i;35 }36 37 for (int i = 1; i < n; ++i)38 leftToRight[i] = Math.max(leftToRight[i], leftToRight[i - 1]);39 40 return leftToRight;41 }42 43 private void reverse(int[] arr, int l, int r) {44 while (l < r)45 swap(arr, l++, r--);46 }47 48 private void swap(int[] arr, int i, int j) {49 final int temp = arr[i];50 arr[i] = arr[j];51 arr[j] = temp;52 }53}54