BackmediumArraysAccenture

Temperature Trend Analyzer Solution

Problem Statement

Temperature Trend Analyzer\nGiven an array nums of integers representing daily temperature readings and a string pattern composed solely of the characters 'A' (increase) and 'D' (decrease), determine the maximum possible length of a subsequence of nums such that the sign of each consecutive difference follows the pattern cyclically. A subsequence is formed by deleting zero or more elements without reordering the remaining ones. The first difference must correspond to the first character of pattern, the second difference to the second character, and after the last character the pattern repeats from the beginning. Return the length of the longest such subsequence; if no two elements satisfy the first character, the answer is 1 (any single element).

Example 1
Input
nums = [30,32,31,35,33,36], pattern = "AD"
Output
6

Explanation: Select the whole array as the subsequence: 30→32 (increase, matches 'A'), 32→31 (decrease, matches 'D'), 31→35 (increase), 35→33 (decrease), 33→36 (increase). The differences follow ADAD... and the subsequence length is 6, which is maximal.

Example 2
Input
nums = [10,9,8,7,6], pattern = "A"
Output
1

Explanation: The pattern requires every consecutive difference to be an increase, but the array is strictly decreasing. The longest subsequence that satisfies the condition consists of any single element, giving length 1.

Example 3
Input
nums = [5,7,6,8,7,9,8], pattern = "DA"
Output
6

Explanation: Choose the subsequence [7,6,8,7,9,8]. Differences: 7→6 (decrease, 'D'), 6→8 (increase, 'A'), 8→7 (decrease, 'D'), 7→9 (increase, 'A'), 9→8 (decrease, 'D'). The pattern D A repeats correctly, yielding a subsequence of length 6, which is the maximum possible.

Constraints

  • 1 <= nums.length <= 100000
  • 1 <= pattern.length <= 100
  • -10^9 <= nums[i] <= 10^9
  • pattern contains only characters 'A' and 'D'
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

Temperature Trend Analyzer — Problem Statement & Solution Guide

ArraysMediumMixed
TimeO(N * M)
|
SpaceO(N * M)

Problem Description

Temperature Trend Analyzer\nGiven an array nums of integers representing daily temperature readings and a string pattern composed solely of the characters 'A' (increase) and 'D' (decrease), determine the maximum possible length of a subsequence of nums such that the sign of each consecutive difference follows the pattern cyclically. A subsequence is formed by deleting zero or more elements without reordering the remaining ones. The first difference must correspond to the first character of pattern, the second difference to the second character, and after the last character the pattern repeats from the beginning. Return the length of the longest such subsequence; if no two elements satisfy the first character, the answer is 1 (any single element).

DSA Pattern Breakdown

DSA Pattern Breakdown

"Temperature Trend Analyzer"

medium

WHY DOES IT MATTER?

This pattern is essential for problems involving sequences with constraints on consecutive elements, such as stock trading with cooldowns, or signal processing where trends must follow specific patterns. It teaches the application of DP with state tracking, a fundamental skill in algorithm design.

OPTIMIZATION CHALLENGE

The key insight is recognizing that the pattern is cyclic, allowing the state to be defined by the current pattern index modulo the pattern length. This reduces the state space and allows for efficient DP transitions.

REAL-WORLD CONNECTION

This is analogous to analyzing stock price trends or sensor data in IoT devices, where you might need to detect the longest period of consistent up/down movements to predict future behavior or trigger alerts.

In interviews, clearly define your DP state and transition function. Start with a brute-force approach to establish the problem's nature, then transition to DP by identifying overlapping subproblems and optimal substructure.

COMPLEXITY AT A GLANCE

⏱ Time:O(N * M)
💾 Space:O(N * M)

Core Theory — Why This Approach?

The problem requires finding the longest subsequence where the differences between consecutive elements follow a cyclic pattern of 'A' (increase) and 'D' (decrease). A naive approach would involve checking all possible subsequences, which is computationally infeasible for large arrays due to the exponential number of combinations. The optimal paradigm is Dynamic Programming, specifically a state-based DP where the state is defined by the current index in the array and the current position in the pattern cycle. This allows us to build the solution incrementally, ensuring that each step adheres to the required trend.

Interview Questions on This Problem

Q1How would you modify your solution if the pattern was not cyclic but a fixed sequence that must be followed exactly once?

You would adjust the DP state to track the position in the pattern without wrapping around. The transition logic would remain similar, but you would stop extending the subsequence once the pattern length is reached, ensuring the pattern is not repeated.

Q2What is the impact on time complexity if the pattern length is much larger than the array length?

The time complexity remains O(N * M), where N is the array length and M is the pattern length. However, if M > N, the effective complexity is bounded by O(N^2) because you cannot have a subsequence longer than the array itself, so the pattern position effectively caps at N.

Q3Can you optimize the space complexity of your DP solution?

Yes, since the DP state at index i only depends on states from previous indices, you can use a 1D array for each pattern position, updating it in-place or using two arrays to reduce space from O(N * M) to O(M) or O(N * M) depending on the specific implementation and whether you need to reconstruct the subsequence.

Examples

Example 1

Input

nums = [30,32,31,35,33,36], pattern = "AD"

Output

6

Explanation: Select the whole array as the subsequence: 30→32 (increase, matches 'A'), 32→31 (decrease, matches 'D'), 31→35 (increase), 35→33 (decrease), 33→36 (increase). The differences follow ADAD... and the subsequence length is 6, which is maximal.

Example 2

Input

nums = [10,9,8,7,6], pattern = "A"

Output

1

Explanation: The pattern requires every consecutive difference to be an increase, but the array is strictly decreasing. The longest subsequence that satisfies the condition consists of any single element, giving length 1.

Example 3

Input

nums = [5,7,6,8,7,9,8], pattern = "DA"

Output

6

Explanation: Choose the subsequence [7,6,8,7,9,8]. Differences: 7→6 (decrease, 'D'), 6→8 (increase, 'A'), 8→7 (decrease, 'D'), 7→9 (increase, 'A'), 9→8 (decrease, 'D'). The pattern D A repeats correctly, yielding a subsequence of length 6, which is the maximum possible.

Constraints

  • 1 <= nums.length <= 100000
  • 1 <= pattern.length <= 100
  • -10^9 <= nums[i] <= 10^9
  • pattern contains only characters 'A' and 'D'

Optimal Approach & Strategy

Use dynamic programming where dp[i][j] represents the length of the longest valid subsequence ending at index i with the pattern position j. Transition by checking if the current element can extend a valid subsequence from previous elements, updating the DP table in O(N * M) time.

Brute Force Approach

Generate all possible subsequences of the array and check if each one follows the given pattern. This approach is exponential in time complexity and is not feasible for large inputs.

Verified Code Solutions

JavaScript Solution
Time: O(N * M)
/**
 * @param {number[]} nums
 * @param {string} pattern
 * @return {number}
 */
var maxSubsequenceLength = function(nums, pattern) {
    const n = nums.length;
    const m = pattern.length;
    if (n === 0 || m === 0) return 0;
    
    // dp[i][j] = max length of subsequence ending at index i,
    // where the next required pattern character is pattern[j]
    const dp = Array.from({ length: n }, () => Array(m).fill(1));
    
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            for (let k = 0; k < i; k++) {
                const diff = nums[i] - nums[k];
                const required = pattern[j];
                if ((required === 'A' && diff > 0) || (required === 'D' && diff < 0)) {
                    const nextJ = (j + 1) % m;
                    dp[i][nextJ] = Math.max(dp[i][nextJ], dp[k][j] + 1);
                }
            }
        }
    }
    
    let result = 0;
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            result = Math.max(result, dp[i][j]);
        }
    }
    
    return result;
};

// Example usage
const nums = [30, 32, 31, 35, 33, 36];
const pattern = "AD";
console.log(maxSubsequenceLength(nums, pattern));

Asked in Top Tech Interviews

Accenture

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.