I am solving Maximum Subarray Sum with One Deletion on LeetCode:
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. For input
arr = [1,-2,0,3]
, output should be4
.
I came up with a recursive solution as below:
class Solution { public: int helper(vector<int>& n, vector<int>& cache, int startIndex) { if(startIndex>=n.size()) return INT_MIN; if(cache[startIndex]!=-1) return cache[startIndex]; int allInclusiveSum=0, sumWithOneDel=0, lowestVal=INT_MAX, maxVal=INT_MIN; for(int i=startIndex; i<n.size(); i++) { allInclusiveSum+=n[i]; maxVal=max(maxVal, allInclusiveSum); if(i!=startIndex) { lowestVal=min(lowestVal, n[i]); sumWithOneDel=allInclusiveSum-lowestVal; maxVal=max(maxVal, sumWithOneDel); } } maxVal=max(maxVal, helper(n, cache, startIndex+1)); return cache[startIndex]=maxVal; } int maximumSum(vector<int>& arr) { int i=0, first=arr[0]; for(i=1; i<arr.size(); i++) if(arr[i]!=first) break; if(i==arr.size()) return first; vector<int> cache(arr.size(), -1); return helper(arr, cache, 0); } };
Unfortunately, this TLEs. Since I call recursively with startIndex+1
, I don't really think I am encountering overlapping sub-problems.
Is there a way I could memoize my solution? If no, why?
std::map
to cache?" and yet I don't see one, so... – tadman