702866. Maximum Sum Bitonic Subsequence

Easy

Maximum Sum Bitonic Subsequence

Summary

The problem is about finding a bitonic subsequence in an array that has the maximum sum. A bitonic sequence is either strictly increasing or strictly decreasing, and a bitonic subsequence is a contiguous portion of a bitonic sequence.

Detailed Explanation

To solve this problem, we will use dynamic programming to build a table where each cell represents the maximum sum of a bitonic subsequence ending at that position. We start by considering all possible subsequences and then select the one with the maximum sum.

Here's the step-by-step breakdown:

  1. Initialize a 2D array dp of size (n x n), where n is the length of the input array.
  2. Iterate over the array from left to right, considering each element as the end point of a bitonic subsequence.
  3. For each element, calculate the maximum sum of a bitonic subsequence ending at that position by considering two cases:
    • The current element forms the peak of the sequence, and the rest of the sequence is decreasing.
    • The current element is part of an increasing sequence that ends before it, and the remaining part of the sequence is decreasing.
  4. Update the dp table with the maximum sum calculated in step 3.
  5. Find the position with the maximum sum in the dp table and return the corresponding subsequence.

Time complexity: O(n^2), where n is the length of the input array. Space complexity: O(n^2), for storing the dynamic programming table.

Here's an ASCII art diagram to illustrate the problem:

1 2 3 4 5
↑ ↑ ↓ ↓

The above diagram represents a bitonic subsequence (1, 2) and then decreasing sequence (3, 4, 5).

Optimized Solutions

Java

View on GeeksforGeeks
public int maxSumBitonicSubsequence(int[] arr) {
    int n = arr.length;
    int[][] dp = new int[n][n];
    
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            if (i == 0) {
                dp[i][j] = arr[j];
            } else {
                dp[i][j] = Math.max(dp[i-1][j-1], arr[j]) + (i == j ? 0 : -arr[j]);
            }
        }
    }
    
    int maxSum = 0;
    for (int i = 0; i < n; i++) {
        maxSum = Math.max(maxSum, dp[n-1][i]);
    }
    
    return maxSum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.