BackmediumArraysZomatoAccenture

Alternating Subsequence Sum Solution

Problem Statement

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.

Example 1
Input
[2, -6, 5, 1, 5, 3]
Output
7

Explanation: The correct alternating subsequence is 2, -6, 5.

Example 2
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
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Alternating Subsequence Sum — Problem Statement & Solution Guide

ArraysMediumMixed
TimeO(n)
|
SpaceO(1)

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

Example 1

Input

[2, -6, 5, 1, 5, 3]

Output

7

Explanation: The correct alternating subsequence is 2, -6, 5.

Example 2

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

No solution currently available for JavaScript. Select another language tab above.

Asked in Top Tech Interviews

ZomatoAccenture

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.