703864. Maximum bitonic subarray sum

Medium

Maximum Bitonic Subarray Sum

Summary

Given a binary array (0s and 1s), find the maximum sum of bitonic subarrays. A bitonic sequence is either strictly increasing or strictly decreasing.

The problem involves arrays, which is one of the tags mentioned. We'll explore different approaches to solve this problem efficiently.

Detailed Explanation

To approach this problem, we can start by understanding what a bitonic sequence is. A bitonic sequence is either strictly increasing or strictly decreasing. So, if we find all the bitonic sequences in the given array and calculate their sums, we can then return the maximum sum among them.

Let's break down the steps to solve this problem:

  1. Initialize two variables: maxSum to store the maximum sum found so far and currentSum to keep track of the current sum being calculated.
  2. Iterate over the array from left to right:
    • If the current element is 0, it means we're entering a decreasing part of the bitonic sequence. In this case, update currentSum with the value of the previous element (since the sequence starts increasing again after this).
    • If the current element is 1, it means we're in an increasing part of the bitonic sequence. Update currentSum by adding the value of the current element.
  3. Keep updating maxSum with the maximum of maxSum and currentSum.
  4. Finally, return maxSum.

Time complexity: O(n), where n is the size of the array.

Space complexity: O(1), as we're only using a constant amount of space to store maxSum, currentSum, and some temporary variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxBitonicSubarraySum(int[] arr) {
    int n = arr.length;
    int maxSum = 0, currentSum = 0;

    for (int i = 0; i < n; i++) {
        if (arr[i] == 0) {
            currentSum = currentSum > 0 ? 1 : 0;
        } else {
            currentSum += arr[i];
        }

        maxSum = Math.max(maxSum, currentSum);
    }

    return maxSum;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.