BackeasyDynamic ProgrammingTCSSwiggy

Monotonic Envelope Engine Solution

Problem Statement

You are given an array of N positive integers. A subsequence of this array is obtained by deleting zero or more elements while preserving the original order. For a chosen subsequence, write down the decimal digits of its elements one after another to form a single digit string. The subsequence is called monotonic if this digit string is non‑decreasing (each digit is less than or equal to the next one). Your task is to determine the maximum possible sum of the integers in any monotonic subsequence. If no non‑empty monotonic subsequence exists, the answer is 0.

Input format:

  • The first line contains a single integer N (1 ≤ N ≤ 10^5).
  • The second line contains N space‑separated integers a1, a2, …, aN (1 ≤ ai ≤ 10^9).

Output format:

  • Output a single integer: the maximum sum achievable by a monotonic subsequence.
Example 1
Input
5 1 12 3 23 4
Output
40

Explanation: The digits of the chosen subsequence 1, 12, 23, 4 are 1|1 2|2 3|4, which form the string 1 1 2 2 3 4 – non‑decreasing. The sum is 1+12+23+4=40, which is the largest possible.

Example 2
Input
4 9 8 7 6
Output
9

Explanation: Each number has a single digit. Any two different digits would violate the non‑decreasing rule (e.g., 9 followed by 8). The best choice is the single number 9, giving a sum of 9.

Example 3
Input
6 10 20 30 40 50 60
Output
0

Explanation: Every number contains a decreasing pair of digits (e.g., 1>0 in 10). Including any such number would break the monotonic property, so no non‑empty monotonic subsequence exists. The answer is 0.

Example 4
Input
3 123 456 789
Output
1368

Explanation: The concatenated digits 1 2 3 4 5 6 7 8 9 are strictly increasing, so the whole array is a valid monotonic subsequence. The sum is 123+456+789=1368.

Example 5
Input
5 11 22 33 44 55
Output
165

Explanation: All numbers have identical digits, so the concatenated string 1 1 2 2 3 3 4 4 5 5 is non‑decreasing. The sum is 11+22+33+44+55=165.

Constraints

  • 1 <= N <= 100000
  • 1 <= ai <= 1000000000
  • Each ai has at most 10 decimal digits
  • The total number of digits across all ai does not exceed 10^6
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

Monotonic Envelope Engine — Problem Statement & Solution Guide

Dynamic ProgrammingEasyDigit DP
TimeO(N)
|
SpaceO(1)

Problem Description

You are given an array of N positive integers. A subsequence of this array is obtained by deleting zero or more elements while preserving the original order. For a chosen subsequence, write down the decimal digits of its elements one after another to form a single digit string. The subsequence is called *monotonic* if this digit string is non‑decreasing (each digit is less than or equal to the next one). Your task is to determine the maximum possible sum of the integers in any monotonic subsequence. If no non‑empty monotonic subsequence exists, the answer is 0.

Input format:

- The first line contains a single integer N (1 ≤ N ≤ 10^5).

- The second line contains N space‑separated integers a1, a2, …, aN (1 ≤ ai ≤ 10^9).

Output format:

- Output a single integer: the maximum sum achievable by a monotonic subsequence.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Monotonic Envelope Engine"

easy

WHY DOES IT MATTER?

The pattern of reducing a complex digit‑concatenation constraint to a simple last‑digit versus first‑digit comparison is essential because it transforms an exponential search into a linear scan. It demonstrates how domain knowledge (digits 0–9) can be leveraged to compress state space and achieve optimal performance.

OPTIMIZATION CHALLENGE

The key insight is that only the last digit of a number influences future choices, and the alphabet size is constant (10). By maintaining the best subsequence length for each possible last digit, we avoid nested loops and reduce the complexity from O(N^2) to O(N).

REAL-WORLD CONNECTION

Consider a log aggregation system where each log entry is a timestamp string. Ensuring that logs are processed in non‑decreasing order of their timestamp digits is analogous to maintaining monotonicity; the algorithm mirrors how a streaming service might keep a rolling window of the latest timestamps to validate order without re‑examining the entire history.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem reduces to finding the longest subsequence of numbers whose concatenated decimal digits form a non‑decreasing string. A key observation is that any number whose own digits are not non‑decreasing can never appear in a valid subsequence, because the internal order would already violate the monotonicity. After filtering such numbers, the remaining numbers can be represented by a pair (firstDigit, lastDigit). For two consecutive numbers in the subsequence, the last digit of the earlier number must be less than or equal to the first digit of the later number. This transforms the problem into a longest‑subsequence problem on a one‑dimensional key (the last digit) with a simple inequality constraint. A naive O(2^N) or O(N^2) DP would be too slow for large N, but because digits are only 0–9 we can keep an array best[10] that stores the best subsequence length ending with each possible last digit. For each number we compute dp = 1 + max(best[0..firstDigit]) and then update best[lastDigit] = max(best[lastDigit], dp). This yields O(N) time and O(1) space.

Interview Questions on This Problem

Q1How would you modify the algorithm if the input array contained negative integers?

Negative numbers introduce a minus sign, which is not a digit. We would first convert each number to its absolute value, then treat the minus sign as a separator that breaks monotonicity. In practice, we would discard any negative number because its string representation would contain a non‑digit character, violating the digit‑only requirement.

Q2In a distributed system, how could you parallelize the computation of the longest monotonic subsequence?

Because the DP depends only on the best subsequence lengths for last digits up to the current number, we can partition the array into chunks and process each chunk sequentially while passing a shared best[10] array between workers. Each worker updates best locally and then merges the results, ensuring that the global best reflects all processed elements.

Q3What would change if the monotonicity condition were strict (each digit < next digit) instead of non‑decreasing?

The inequality in the DP would change from lastDigit <= firstDigit to lastDigit < firstDigit. Consequently, when computing dp for a number we would take the maximum over best[0..firstDigit-1] instead of best[0..firstDigit]. All other steps remain identical.

Examples

Example 1

Input

5
1 12 3 23 4

Output

40

Explanation: The digits of the chosen subsequence 1, 12, 23, 4 are 1|1 2|2 3|4, which form the string 1 1 2 2 3 4 – non‑decreasing. The sum is 1+12+23+4=40, which is the largest possible.

Example 2

Input

4
9 8 7 6

Output

9

Explanation: Each number has a single digit. Any two different digits would violate the non‑decreasing rule (e.g., 9 followed by 8). The best choice is the single number 9, giving a sum of 9.

Example 3

Input

6
10 20 30 40 50 60

Output

0

Explanation: Every number contains a decreasing pair of digits (e.g., 1>0 in 10). Including any such number would break the monotonic property, so no non‑empty monotonic subsequence exists. The answer is 0.

Example 4

Input

3
123 456 789

Output

1368

Explanation: The concatenated digits 1 2 3 4 5 6 7 8 9 are strictly increasing, so the whole array is a valid monotonic subsequence. The sum is 123+456+789=1368.

Example 5

Input

5
11 22 33 44 55

Output

165

Explanation: All numbers have identical digits, so the concatenated string 1 1 2 2 3 3 4 4 5 5 is non‑decreasing. The sum is 11+22+33+44+55=165.

Constraints

  • 1 <= N <= 100000
  • 1 <= ai <= 1000000000
  • Each ai has at most 10 decimal digits
  • The total number of digits across all ai does not exceed 10^6

Optimal Approach & Strategy

Filter out numbers with decreasing internal digits. For each remaining number, compute dp = 1 + max(best[0..firstDigit]) where best[d] stores the longest subsequence ending with last digit d. Update best[lastDigit] = max(best[lastDigit], dp). This runs in linear time.

Brute Force Approach

Enumerate all 2^N subsequences, concatenate their digits, and check if the resulting string is non‑decreasing. Keep the longest valid subsequence found.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function monotonicEnvelope(nums) {
      let monotonicEnvelope = [nums[0]];
      for (let i = 1; i < nums.length; i++) {
         if (nums[i] > monotonicEnvelope[monotonicEnvelope.length - 1]) {
            monotonicEnvelope.push(nums[i]);
         } else {
            monotonicEnvelope[monotonicEnvelope.length - 1] = nums[i];
         }
      }
      return monotonicEnvelope;
   }

Asked in Top Tech Interviews

TCSSwiggy

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.