512. Maximum Alternating Subarray Sum
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the maximum sum of a contiguous subarray with alternating signs. For a subarray starting at index i, the sum is nums[i] - nums[i+1] + nums[i+2] - .... The key challenge is that the sign of each number nums[k] depends on its position relative to the start of the subarray i, not its absolute index k. This structure suggests a dynamic programming approach, as a simple application of Kadane's algorithm for maximum subarray sum doesn't work directly.
Solution
Maximum Alternating Subarray Sum in Python
class Solution:
def maximumAlternatingSubarraySum(self, nums: List[int]) -> int:
n = len(nums)
if n == 0:
return 0
# even_sum: max alternating sum for a subarray ending at current index, having ODD length (last element added)
# odd_sum: max alternating sum for a subarray ending at current index, having EVEN length (last element subtracted)
even_sum = nums[0]
# A very small number to represent an invalid/impossible state initially
odd_sum = -float('inf')
max_so_far = nums[0]
for i in range(1, n):
current_num = nums[i]
# We need to use temps because new odd_sum depends on old even_sum
temp_even_sum = max(current_num, odd_sum + current_num)
temp_odd_sum = even_sum - current_num
even_sum = temp_even_sum
odd_sum = temp_odd_sum
# The maximum sum could be from an odd-length or even-length subarray
max_so_far = max(max_so_far, even_sum, odd_sum)
return max_so_far
Maximum Alternating Subarray Sum in Java
class Solution {
public long maximumAlternatingSubarraySum(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
// evenSum: max alternating sum for a subarray ending at current index, having ODD length (last element added)
// oddSum: max alternating sum for a subarray ending at current index, having EVEN length (last element subtracted)
long evenSum = nums[0];
// A very small number to represent an invalid/impossible state initially
long oddSum = Long.MIN_VALUE / 2; // Avoid overflow when adding
long maxSoFar = nums[0];
for (int i = 1; i < n; ++i) {
long currentNum = nums[i];
// We need to use temps because new oddSum depends on old evenSum
long tempEvenSum = Math.max(currentNum, oddSum + currentNum);
long tempOddSum = evenSum - currentNum;
evenSum = tempEvenSum;
oddSum = tempOddSum;
// The maximum sum could be from an odd-length or even-length subarray
maxSoFar = Math.max(maxSoFar, Math.max(evenSum, oddSum));
}
return maxSoFar;
}
}
Maximum Alternating Subarray Sum in C++
class Solution {
public:
long long maximumAlternatingSubarraySum(vector<int>& nums) {
int n = nums.size();
if (n == 0) {
return 0;
}
// even_sum: max alternating sum for a subarray ending at current index, having ODD length (last element added)
// odd_sum: max alternating sum for a subarray ending at current index, having EVEN length (last element subtracted)
long long even_sum = nums[0];
// A very small number to represent an invalid/impossible state initially
long long odd_sum = -2e18;
long long max_so_far = nums[0];
for (int i = 1; i < n; ++i) {
long long current_num = nums[i];
// We need to use temps because new odd_sum depends on old even_sum
long long temp_even_sum = max(current_num, odd_sum + current_num);
long long temp_odd_sum = even_sum - current_num;
even_sum = temp_even_sum;
odd_sum = temp_odd_sum;
// The maximum sum could be from an odd-length or even-length subarray
max_so_far = max({max_so_far, even_sum, odd_sum});
}
return max_so_far;
}
};
Maximum Alternating Subarray Sum in TypeScript
function maximumAlternatingSubarraySum(nums: number[]): number {
const n = nums.length;
if (n === 0) {
return 0;
}
// evenSum: max alternating sum for a subarray ending at current index, having ODD length (last element added)
// oddSum: max alternating sum for a subarray ending at current index, having EVEN length (last element subtracted)
let evenSum = BigInt(nums[0]);
// A very small number to represent an invalid/impossible state initially
let oddSum = BigInt(-1e18);
let maxSoFar = BigInt(nums[0]);
for (let i = 1; i < n; ++i) {
const currentNum = BigInt(nums[i]);
// We need to use temps because new oddSum depends on old evenSum
const tempEvenSum = oddSum + currentNum > currentNum ? oddSum + currentNum : currentNum;
const tempOddSum = evenSum - currentNum;
evenSum = tempEvenSum;
oddSum = tempOddSum;
// The maximum sum could be from an odd-length or even-length subarray
if (evenSum > maxSoFar) maxSoFar = evenSum;
if (oddSum > maxSoFar) maxSoFar = oddSum;
}
// The problem statement implies the result fits in a standard number type, though intermediate sums might not.
// BigInt is safer for calculations. Return value should be Number.
return Number(maxSoFar);
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.