702866. Maximum Sum Bitonic Subsequence
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:
- Initialize a 2D array
dpof size(n x n), wherenis the length of the input array. - Iterate over the array from left to right, considering each element as the end point of a bitonic subsequence.
- 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.
- Update the
dptable with the maximum sum calculated in step 3. - Find the position with the maximum sum in the
dptable 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
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;
}