Description:
In this post, I’m sharing an alternate solution to the maximum subarray sum problem using prefix sums. This method optimizes the process by maintaining a running sum and calculating the difference between the current sum and the minimum sum encountered so far. Explanation:
- Prefix Sums: We use a temp vector that stores pairs of the index and the cumulative sum at that point.
- MinSum and MaxSum: These are used to keep track of the minimum sum encountered so far and the maximum cumulative sum.
- Difference Calculation: For each iteration, the difference between the current cumulative sum and the minimum cumulative sum is calculated, which gives us the largest subarray sum efficiently.
This approach ensures that we only traverse the array once, making the time complexity O(n).
#define ll long long int
long long maxSubarraySum(vector<int> arr, int n)
{
vector<pair<ll, ll>> temp(n);
ll minSum = 0, maxSum = INT_MIN, diff = INT_MIN;
for (ll i = 0; i < n; i++) {
temp[i].first = i;
if (i > 0) {
temp[i].second = temp[i - 1].second + arr[i];
} else {
temp[i].second = arr[i];
}
minSum = min(minSum, temp[i].second);
maxSum = max(maxSum, temp[i].second);
diff = max(diff, temp[i].second - minSum);
}
return diff;
}