BackmediumArrays Uber

Temperature Fluctuation Analysis 2 Solution

Problem Statement

Given an array of temperature readings, find the maximum sum of an alternating subsequence where the difference between adjacent elements is either increasing or decreasing.

Example 1
Input
[3, 7, 5, 2, 9, 1, 4, 6, 8, 0]
Output
27

Explanation: Step-by-step: We start with the first element 3. Then, we find the next element 7 which has an increasing difference with 3. Next, we find the element 5 which has a decreasing difference with 7. Then, we find the element 2 which has an increasing difference with 5. Next, we find the element 9 which has an increasing difference with 2. Then, we find the element 1 which has a decreasing difference with 9. Next, we find the element 4 which has an increasing difference with 1. Then, we find the element 6 which has an increasing difference with 4. Next, we find the element 8 which has an increasing difference with 6. Finally, we find the element 0 which has a decreasing difference with 8. The sum of this alternating subsequence is 3 + 7 - 5 + 2 + 9 - 1 + 4 + 6 - 8 + 0 = 27.

Example 2
Input
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Output
150

Explanation: Step-by-step: We start with the first element 10. Then, we find the next element 20 which has an increasing difference with 10. Next, we find the element 30 which has an increasing difference with 20. Then, we find the element 40 which has an increasing difference with 30. Next, we find the element 50 which has an increasing difference with 40. Then, we find the element 60 which has an increasing difference with 50. Next, we find the element 70 which has an increasing difference with 60. Then, we find the element 80 which has an increasing difference with 70. Next, we find the element 90 which has an increasing difference with 80. Finally, we find the element 100 which has an increasing difference with 90. The sum of this alternating subsequence is 10 + 20 + 30 + 40 + 50 + 60 + 70 + 80 + 90 + 100 = 500. However, we need to find the maximum sum of an alternating subsequence. We can achieve this by alternating between increasing and decreasing differences. One possible alternating subsequence is 10 - 20 + 30 - 40 + 50 - 60 + 70 - 80 + 90 - 100 = 150.

Constraints

  • 1 <= length of array <= 1000
  • -10000 <= each element in array <= 10000
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free