Palindromic Subarray Sum Problem
Description
LeetCode Problem 3985.
You are given an integer array nums.
Return the maximum possible sum of a subarray of nums that is a palindrome.
Example 1:
Input: nums = [10,10]
Output: 20
Explanation:
The whole array [10,10] is a palindrome. Therefore, the maximum sum is 10 + 10 = 20.
Example 2:
Input: nums = [1,2,3,2,1,5,6]
Output: 9
Explanation:
The contiguous subarray [1,2,3,2,1] is a palindrome. Its sum is 1 + 2 + 3 + 2 + 1 = 9 and it is the maximum sum.
Example 3:
Input: nums = [7,1,2,1,7,3,4,3,4]
Output: 18
Explanation:
The contiguous subarray [7,1,2,1,7] is a palindrome. Its sum is 7 + 1 + 2 + 1 + 7 = 18 and it is the maximum sum.
Example 4:
Input: nums = [1,2,3,4,5]
Output: 5
Explanation:
No subarray with length greater than 1 is a palindrome. The largest element in the array is 5. Therefore, the answer is 5.
Example 5:
Input: nums = [1000]
Output: 1000
Explanation:
The subarray with only one element is a palindrome. Therefore, the answer is 1000.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Manacher's algorithm with prefix sums
All numbers are positive, so for a fixed center the longest palindrome around it also has the largest sum. It is enough to find, for every center, the longest palindromic subarray, and take the best sum among them. Every single element is a palindrome, so the answer is at least max(nums).
Manacher's algorithm computes the longest palindrome radius for every odd center and every even center in O(n) total by reusing the mirror image of the palindrome that reaches furthest to the right. With a prefix-sum array, the sum of each longest palindrome is read in O(1). Sums reach about 10^14, so use 64-bit integers.
Complexity: time O(n), space O(n).
class Solution:
def getSum(self, nums: List[int]) -> int:
n = len(nums)
pre = [0] * (n + 1)
for i, x in enumerate(nums):
pre[i + 1] = pre[i] + x
ans = max(nums)
# Manacher: d1[i] = number of odd palindromes centred at i, d2[i] = even ones centred between i - 1 and i
d1 = [0] * n
l, r = 0, -1
for i in range(n):
k = 1 if i > r else min(d1[l + r - i], r - i + 1)
while i - k >= 0 and i + k < n and nums[i - k] == nums[i + k]:
k += 1
d1[i] = k
if i + k - 1 > r:
l, r = i - k + 1, i + k - 1
ans = max(ans, pre[i + k] - pre[i - k + 1])
d2 = [0] * n
l, r = 0, -1
for i in range(n):
k = 0 if i > r else min(d2[l + r - i + 1], r - i + 1)
while i - k - 1 >= 0 and i + k < n and nums[i - k - 1] == nums[i + k]:
k += 1
d2[i] = k
if i + k - 1 > r:
l, r = i - k, i + k - 1
if k > 0:
ans = max(ans, pre[i + k] - pre[i - k])
return ans