Alternating Subsequence Sum — Problem Statement & Solution Guide
Problem Description
You are given an array of integers temperatures, find the maximum sum of an alternating subsequence where the difference between adjacent elements is either strictly increasing or strictly decreasing.
Examples
Input
[2, -6, 5, 1, 5, 3]
Output
7
Explanation: The correct alternating subsequence is 2, -6, 5.
Input
[1, 5, 3]
Output
8
Explanation: Step-by-step: with input [1, 5, 3], we first find the maximum increasing subsequence sum (1, 5) which is 6. Then, we find the maximum decreasing subsequence sum (5, 3) which is 2. The alternating subsequence sum is 6 + 2 = 8.
Constraints
- 1 <= length of array <= 1000
- -10000 <= each element in array <= 10000
Optimal Approach & Strategy
The optimal approach involves using dynamic programming to track the maximum sum of alternating subsequences ending at each position in the array, allowing for a more efficient solution with a time complexity of O(n^2).
Brute Force Approach
A brute-force approach would involve generating all possible subsequences of the given array and checking each one to see if it meets the condition of having alternating increasing and decreasing differences, resulting in a time complexity of O(2^n). This approach is not efficient for large inputs.
Verified Code Solutions
class Solution {
public int alternatingSubsequenceSum(int[] temperatures) {
int maxInc = Integer.MIN_VALUE;
int maxDec = Integer.MIN_VALUE;
for (int temp : temperatures) {
maxInc = Math.max(maxInc, maxDec + temp);
maxDec = Math.max(maxDec, maxInc - temp);
}
return Math.max(maxInc, maxDec);
}
}def alternatingSubsequenceSum(temperatures):
maxInc = maxDec = float('-inf')
for temp in temperatures:
maxInc = max(maxInc, maxDec + temp)
maxDec = max(maxDec, maxInc - temp)
return max(maxInc, maxDec)Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.