Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximize point to reduce Array by replacing Subarray with its sum
Next article icon

Maximize non decreasing Array size by replacing Subarray with sum

Last Updated : 11 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N. In one operation only one subarray can be selected and replaced with the sum of the subarray. The task is to find the maximum size of the array after making it non-decreasing.

Examples:

Input: N = 5, arr[] = {5, 1, 6, 6, 6}
Output: 4
Explanation: maximum size non-decreasing array, in this case, is {6, 6, 6, 6} which is obtained by replacing subarray(0, 1) = arr[0] + arr[1] = 6

Input: N = 9, arr[] = {5, 1, 6, 7, 7, 1, 6, 4, 5 }
Output: 6
Explanation: maximum size non-decreasing array, in this case, is {5, 7, 7, 7, 7, 9} which is obtained by replacing subarray(1, 2) = arr[1] + arr[2] = 7. Subarray(5, 6) = arr[5] + arr[6] = 7. Subarray(7, 8) = arr[7] + arr[8] = 9

Table of Content

  • [Naive Approach] Using Dynamic Programming (DP) - O(n^2) time and O(n) space
  • [Expected Approach] Using DP + Binary Search + Monotonic Stack - O(n log(n)) time and O(n) space

[Naive Approach] Using Dynamic Programming (DP) - O(n^2) time and O(n) space

The idea behind this solution is to use dynamic programming to solve the problem, the main observation is that the maximum length of a non-decreasing array that can be created up to the current index i depends on the maximum length of a non-decreasing array that can be created up to a previous index j, where j < i. This is because the operation of replacing a subarray with its sum can only be performed on a contiguous subarray, and the resulting array must be non-decreasing.

By using dynamic programming, the solution can efficiently keep track of the maximum length of a non-decreasing array that can be created up to each index, and use this information to determine the maximum length that can be created up to the current index.

Below are the detailed steps of above intuition:

1. Initialize Arrays:

  • prefix: Stores the cumulative sum of elements up to each index.
  • dp: Stores the maximum length of the non-decreasing subarray that can be formed ending at each index.
  • last: Stores the maximum subarray sum that ends at each index.

2. Calculate the prefix sum for each index.
3. Dynamic Programming Approach:

  • Iterate through each index i starting from the second element.
    • For each i, check all previous indices j to find the longest subarray that can be extended to include i.
    • Update dp[i] and last[i] based on the conditions:
      • If the current prefix sum prefix[i] is greater than or equal to the required sum last[j] + prefix[j], update dp[i] to dp[j] + 1 and set last[i] to prefix[i] - prefix[j]

4. Result: The value at dp[n - 1] will gives the length of the longest non-decreasing subarray that can be formed.

Code Implementation:

C++
#include <bits/stdc++.h> using namespace std;  // Function to find the maximum length of a non-decreasing // array that can be made after applying operations int findMaximumLength(vector<int>& nums) {     int n = nums.size();     if (n == 0)         return 0;      // Prefix sum array to store cumulative sums     vector<long long> prefix(n), last(n), dp(n, 1);      // Initializing the prefix sum array     prefix[0] = nums[0];     for (int i = 1; i < n; i++) {         prefix[i] = prefix[i - 1] + nums[i];     }      // Initializing the last array     last[0] = nums[0];      // Dynamic Programming approach to find the maximum     // length     for (int i = 1; i < n; i++) {         bool found = false;         for (int j = i - 1; j >= 0; j--) {              // Check if current prefix sum is greater             // than or equal to the required sum             if (prefix[i] >= last[j] + prefix[j]) {                 dp[i] = dp[j] + 1;                 last[i] = prefix[i] - prefix[j];                 found = true;                 break;             }         }          // If no valid subarray is found, set last[i] to         // prefix[i]         if (!found)             last[i] = prefix[i];     }      // The result is the dp[n - 1] value in dp array     return dp[n - 1]; }  int main() {      // Test case 1     vector<int> nums1 = { 5, 1, 6, 6, 6 };     cout << findMaximumLength(nums1) << endl;      // Test case 2     vector<int> nums2 = { 5, 1, 6, 7, 7, 1, 6, 4, 5 };     cout << findMaximumLength(nums2) << endl;      return 0; } 
Java
import java.util.*;  public class Main {      // Function to find the maximum length of a     // non-decreasing array that can be made after applying     // operations     public static int findMaximumLength(List<Integer> nums)     {         int n = nums.size(); // Length of the input list          // If the list is empty, return 0 as there is no         // array to process         if (n == 0)             return 0;          // Arrays to store prefix sums, the last element of         // the longest subarray ending at each position, and         // DP values         long[] prefix = new long[n];         long[] last = new long[n];         int[] dp = new int[n];          // Initializing the dp array with 1 since each         // element is at least a subarray of length 1         Arrays.fill(dp, 1);          // Initializing the prefix sum array         prefix[0] = nums.get(0);         for (int i = 1; i < n; i++) {             prefix[i] = prefix[i - 1] + nums.get(i);         }          // Initializing the last array with the first         // element         last[0] = nums.get(0);          // Dynamic Programming approach to find the maximum         // length         for (int i = 1; i < n; i++) {              // Flag to check if a valid subarray ending at i             // is found             boolean found = false;              // Check all previous elements to find the             // longest valid subarray ending at i             for (int j = i - 1; j >= 0; j--) {                  // If the current prefix sum is greater than                 // or equal to the required sum                 if (prefix[i] >= last[j] + prefix[j]) {                      // Update dp value for the current                     // position                     dp[i] = dp[j] + 1;                      // Update the last element of the                     // longest subarray ending at i                     last[i] = prefix[i] - prefix[j];                      // Set the flag as true since a valid                     // subarray is found                     found = true;                      // Exit the loop as we found the longest                     // valid subarray ending at i                     break;                 }             }              // If no valid subarray is found, set last[i] to             // prefix[i]             if (!found)                 last[i] = prefix[i];         }          // The result is the dp[n - 1] value in dp array,         // which contains the maximum length         return dp[n - 1];     }      // Driver Code     public static void main(String[] args)     {         // Test case 1         List<Integer> nums1 = Arrays.asList(5, 1, 6, 6, 6);         System.out.println(             findMaximumLength(nums1));           // Test case 2         List<Integer> nums2             = Arrays.asList(5, 1, 6, 7, 7, 1, 6, 4, 5);         System.out.println(             findMaximumLength(nums2));      } } 
Python
def find_maximum_length(nums):     n = len(nums)  # Length of the input list     if n == 0:         return 0  # If the list is empty, return 0 as there is no array to process      # Prefix sum array to store cumulative sums     prefix = [0] * n     last = [0] * n      # Initializing the dp array with 1 since each element     # is at least a subarray of length 1     dp = [1] * n      # Initializing the prefix sum array     prefix[0] = nums[0]     for i in range(1, n):         prefix[i] = prefix[i - 1] + nums[i]      # Initializing the last array with the first element     last[0] = nums[0]      # Dynamic Programming approach to find the maximum length     for i in range(1, n):        # Flag to check if a valid subarray ending at i is found         found = False          # Check all previous elements to find the longest valid         # subarray ending at i         for j in range(i - 1, -1, -1):              # If the current prefix sum is greater than or equal             # to the required sum             if prefix[i] >= last[j] + prefix[j]:                # Update dp value for the current position                 dp[i] = dp[j] + 1                  # Update the last element of the longest subarray                 #  ending at i                 last[i] = prefix[i] - prefix[j]                  # Set the flag as true since a valid subarray is found                 found = True                  # Exit the loop as we found the longest valid                 # subarray ending at i                 break          # If no valid subarray is found, set last[i] to prefix[i]         if not found:             last[i] = prefix[i]      # The result is the dp[n - 1] value in dp array, which     # contains the maximum length     return dp[n - 1]   # Driver Code if __name__ == "__main__":     # Test case 1     nums1 = [5, 1, 6, 6, 6]     print(find_maximum_length(nums1))      # Test case 2     nums2 = [5, 1, 6, 7, 7, 1, 6, 4, 5]     print(find_maximum_length(nums2)) 
C#
using System; using System.Collections.Generic;  public class Program {     // Function to find the maximum length of a     // non-decreasing array that can be made after applying     // operations     public static int FindMaximumLength(List<int> nums)     {         int n = nums.Count; // Length of the input list          // If the list is empty, return 0 as there is no         // array to process         if (n == 0)             return 0;          // Arrays to store prefix sums, the last element of         // the longest subarray ending at each position, and         // DP values         long[] prefix = new long[n];         long[] last = new long[n];         int[] dp = new int[n];          // Initializing the dp array with 1 since each         // element is at least a subarray of length 1         Array.Fill(dp, 1);          // Initializing the prefix sum array         prefix[0] = nums[0];         for (int i = 1; i < n; i++) {             prefix[i] = prefix[i - 1] + nums[i];         }          // Initializing the last array with the first         // element         last[0] = nums[0];          // Dynamic Programming approach to find the maximum         // length         for (int i = 1; i < n; i++) {              // Flag to check if a valid subarray ending at i             // is found             bool found = false;              // Check all previous elements to find the             // longest valid subarray ending at i             for (int j = i - 1; j >= 0; j--) {                  // If the current prefix sum is greater than                 // or equal to the required sum                 if (prefix[i] >= last[j] + prefix[j]) {                      // Update dp value for the current                     // position                     dp[i] = dp[j] + 1;                      // Update the last element of the                     // longest subarray ending at i                     last[i] = prefix[i] - prefix[j];                      // Set the flag as true since a valid                     // subarray is found                     found = true;                      // Exit the loop as we found the longest                     // valid subarray ending at i                     break;                 }             }              // If no valid subarray is found, set last[i] to             // prefix[i]             if (!found)                 last[i] = prefix[i];         }          // The result is the dp[n - 1] value in dp array,         // which contains the maximum length         return dp[n - 1];     }      // Driver Code     public static void Main()     {         // Test case 1         List<int> nums1 = new List<int>{ 5, 1, 6, 6, 6 };         Console.WriteLine(FindMaximumLength(nums1));          // Test case 2         List<int> nums2             = new List<int>{ 5, 1, 6, 7, 7, 1, 6, 4, 5 };         Console.WriteLine(FindMaximumLength(nums2));     } } 
JavaScript
// Function to find the maximum length of a non-decreasing array // that can be made after applying operations function findMaximumLength(nums) {      // Length of the input array     const n = nums.length;       // If the array is empty, return 0 as there is     // no array to process     if (n === 0)         return 0;      // Arrays to store prefix sums, the last element     // of the longest subarray ending at each position,     // and DP values     const prefix = new Array(n).fill(0);     const last = new Array(n).fill(0);       // Initializing the dp array with 1 since each      // element is at least a subarray of length 1     const dp = new Array(n).fill(1);      // Initializing the prefix sum array     prefix[0] = nums[0];     for (let i = 1; i < n; i++) {         prefix[i] = prefix[i - 1] + nums[i];     }      // Initializing the last array with the first element     last[0] = nums[0];      // Dynamic Programming approach to find the     // maximum length     for (let i = 1; i < n; i++) {          // Flag to check if a valid subarray ending         // at i is found         let found = false;           // Check all previous elements to find the         // longest valid subarray ending at i         for (let j = i - 1; j >= 0; j--) {              // If the current prefix sum is greater             // than or equal to the required sum             if (prefix[i] >= last[j] + prefix[j]) {                  // Update dp value for the current position                 dp[i] = dp[j] + 1;                   // Update the last element of the longest                 // subarray ending at i                 last[i] = prefix[i] - prefix[j];                   // Set the flag as true since a valid                 // subarray is found                 found = true;                   // Exit the loop as we found the longest                 // valid subarray ending at i                 break;             }         }          // If no valid subarray is found, set last[i] to prefix[i]         if (!found)             last[i] = prefix[i];     }      // The result is the dp[n - 1] value in dp array,     // which contains the maximum length     return dp[n - 1]; }  // Driver Code // Test case 1 const nums1 = [5, 1, 6, 6, 6]; console.log(findMaximumLength(nums1));  // Test case 2 const nums2 = [5, 1, 6, 7, 7, 1, 6, 4, 5]; console.log(findMaximumLength(nums2)); 

Output
4 6 

Time Complexity: O(n2)
Auxiliary Space: O(n)

[Expected Approach] Using DP + Binary Search + Monotonic Stack - O(n log(n)) time and O(n) space

The problem is all about, we need to divide the array into subarrays such that replacing each subarray with its sum results in a non-decreasing array. At any index i, we need to determine the maximum number of subarrays that can be formed from the start up to i while maintaining the non-decreasing property.

We always have a minimum answer of 1 at any index (from 0 to i). We need to look how can we maximize our answer for ith index. Maximizing our answer for each index gives us a hint that our answer for ith index will always be >= (i-1)th index, as if answer for ith index comes to be smaller than (i-1)th index, we can always add ith element to subarray which has (i-1)th element and get our answer for ith index = answer for (i-1)th index.

Lets look at our dp states and transititons:

Create a dp array, where dp[i] as the best answer for the subarray ending at index i.

To find dp[i], we need to look for an index j (where 0 <= j < i) such that the sum of the subarray from j+1 to i is greater than or equal to the sum of the subarray that includes arr[j] (let's call this last[j]). This can be represented as

  • prefixsum[i] - prefixsum[j] ≥ sumlast[j]
  • prefixsum[i] ≥ sumlast[j] + prefixsum[j]

Here, last[i] is defined as prefixsum[i] - prefixsum[j]. For each index i, any index j satisfying the above condition can be considered for calculating dp[i]. Thus: dp[i] = max(dp[j]+1) for all 0 ≤ j < i. We will look for bigger value to j to maximise the result at dp[j].

Below are the detailed steps of above intuition:

  • Calculate the prefix sums of the array.
  • Initialize a vector stk where each element is a pair consisting of (prefix[index] + sumlast[index], index).
  • For every index i, perform a binary search to find the index j such that (sumlast[j] + prefixsum[j] <= prefixsum[i]) and is closest to i.
  • Update dp[i] = dp[j] + 1.
  • Maintain the monotonic stack property by removing elements that do not satisfy the condition because this will help use to do binary search on monotonic stack.

Code Implementation:

C++
#include <bits/stdc++.h> using namespace std;  // Function to find the maximum length of a non-decreasing // array that can be made after applying operations int findMaximumLength(vector<int>& arr) {     // Length of the input array     int n = arr.size();      // prefixSum stores the prefix sums of the arr array     vector<long long> prefixSum(n + 1, 0);      // dp stores the maximum length of a non-decreasing     // subarray ending at each index     vector<int> dp(n + 1, 0);      // Calculate prefix sums     for (int i = 1; i <= n; i++)         prefixSum[i] = prefixSum[i - 1] + arr[i - 1];      // stk stores pairs of {value, index} to maintain     // potential maximum lengths     vector<vector<long long> > stk;     stk.push_back({ 0, 0 });      // Iterate over the array to find the maximum length     for (int i = 1; i <= n; i++) {         int low = 0, high = stk.size() - 1;         int j = 0;          // Binary search to find the largest j such that         // prefixSum[j] <= prefixSum[i]         while (low <= high) {             int mid = low + (high - low) / 2;              if (stk[mid][0] <= prefixSum[i]) {                 j = max(j, mid);                 low = mid + 1;             }             else {                 high = mid - 1;             }         }          // Index of the largest valid prefix sum         int index = stk[j][1];          // Update dp[i] to reflect the maximum length of         // non-decreasing subarray ending at i         dp[i] = dp[index] + 1;          // Calculate the new value to be added to stk         long long currLast             = 2 * prefixSum[i] - prefixSum[index];          // Maintain the stack property by removing elements         // that do not satisfy the condition         while (stk.back()[0] >= currLast)             stk.pop_back();          // Add the new value and index to stk         stk.push_back({ currLast, i });     }      // The result is the maximum length of non-decreasing     // subarray that can be obtained     return dp[n]; }  // Driver code to test the above function int main() {     // Test case 1     vector<int> nums1 = { 5, 1, 6, 6, 6 };     cout << findMaximumLength(nums1) << endl;      // Test case 2     vector<int> nums2 = { 5, 1, 6, 7, 7, 1, 6, 4, 5 };     cout << findMaximumLength(nums2) << endl;      return 0; } 
Java
import java.util.*;  public class Main {      // Function to find the maximum length of a     // non-decreasing array that can be made after applying     // operations     public static int findMaximumLength(List<Integer> arr)     {         // Length of the input array         int n = arr.size();          // prefixSum stores the prefix sums of the arr array         long[] prefixSum = new long[n + 1];          // dp stores the maximum length of a non-decreasing         // subarray ending at each index         int[] dp = new int[n + 1];          // Calculate prefix sums         for (int i = 1; i <= n; i++)             prefixSum[i]                 = prefixSum[i - 1] + arr.get(i - 1);          // stk stores pairs of {value, index} to maintain         // potential maximum lengths         List<long[]> stk = new ArrayList<>();         stk.add(new long[] { 0, 0 });          // Iterate over the array to find the maximum length         for (int i = 1; i <= n; i++) {             int low = 0, high = stk.size() - 1;             int j = 0;              // Binary search to find the largest j such that             // prefixSum[j] <= prefixSum[i]             while (low <= high) {                 int mid = low + (high - low) / 2;                  if (stk.get(mid)[0] <= prefixSum[i]) {                     j = Math.max(j, mid);                     low = mid + 1;                 }                 else {                     high = mid - 1;                 }             }              // Index of the largest valid prefix sum             int index = (int)stk.get(j)[1];              // Update dp[i] to reflect the maximum length of             // non-decreasing subarray ending at i             dp[i] = dp[index] + 1;              // Calculate the new value to be added to stk             long currLast                 = 2 * prefixSum[i] - prefixSum[index];              // Maintain the stack property by removing             // elements that do not satisfy the condition             while (stk.get(stk.size() - 1)[0] >= currLast)                 stk.remove(stk.size() - 1);              // Add the new value and index to stk             stk.add(new long[] { currLast, i });         }          // The result is the maximum length of         // non-decreasing subarray that can be obtained         return dp[n];     }      // Driver code to test the above function     public static void main(String[] args)     {         // Test case 1         List<Integer> nums1 = Arrays.asList(5, 1, 6, 6, 6);         System.out.println(             findMaximumLength(nums1)); // Expected output          // Test case 2         List<Integer> nums2             = Arrays.asList(5, 1, 6, 7, 7, 1, 6, 4, 5);         System.out.println(             findMaximumLength(nums2)); // Expected output     } } 
Python
def find_maximum_length(arr):     # Length of the input array     n = len(arr)      # prefixSum stores the prefix sums of the arr array     prefixSum = [0] * (n + 1)      # dp stores the maximum length of a non-decreasing     # subarray ending at each index     dp = [0] * (n + 1)      # Calculate prefix sums     for i in range(1, n + 1):         prefixSum[i] = prefixSum[i - 1] + arr[i - 1]      # stk stores pairs of {value, index} to maintain     # potential maximum lengths     stk = [[0, 0]]      # Iterate over the array to find the maximum length     for i in range(1, n + 1):         low, high = 0, len(stk) - 1         j = 0          # Binary search to find the largest j such that         # prefixSum[j] <= prefixSum[i]         while low <= high:             mid = low + (high - low) // 2              if stk[mid][0] <= prefixSum[i]:                 j = max(j, mid)                 low = mid + 1             else:                 high = mid - 1          # Index of the largest valid prefix sum         index = stk[j][1]          # Update dp[i] to reflect the maximum length of         # non-decreasing subarray ending at i         dp[i] = dp[index] + 1          # Calculate the new value to be added to stk         currLast = 2 * prefixSum[i] - prefixSum[index]          # Maintain the stack property by removing elements         # that do not satisfy the condition         while stk[-1][0] >= currLast:             stk.pop()          # Add the new value and index to stk         stk.append([currLast, i])      # The result is the maximum length of non-decreasing     # subarray that can be obtained     return dp[n]   # Driver code to test the above function if __name__ == "__main__":     # Test case 1     nums1 = [5, 1, 6, 6, 6]     print(find_maximum_length(nums1))      # Test case 2     nums2 = [5, 1, 6, 7, 7, 1, 6, 4, 5]     print(find_maximum_length(nums2)) 
C#
using System; using System.Collections.Generic;  public class Program {     // Function to find the maximum length of a     // non-decreasing array that can be made after applying     // operations     public static int FindMaximumLength(List<int> arr)     {         // Length of the input array         int n = arr.Count;          // prefixSum stores the prefix sums of the arr array         long[] prefixSum = new long[n + 1];          // dp stores the maximum length of a non-decreasing         // subarray ending at each index         int[] dp = new int[n + 1];          // Calculate prefix sums         for (int i = 1; i <= n; i++)             prefixSum[i] = prefixSum[i - 1] + arr[i - 1];          // stk stores pairs of {value, index} to maintain         // potential maximum lengths         List<long[]> stk = new List<long[]>();         stk.Add(new long[] { 0, 0 });          // Iterate over the array to find the maximum length         for (int i = 1; i <= n; i++) {             int low = 0, high = stk.Count - 1;             int j = 0;              // Binary search to find the largest j such that             // prefixSum[j] <= prefixSum[i]             while (low <= high) {                 int mid = low + (high - low) / 2;                  if (stk[mid][0] <= prefixSum[i]) {                     j = Math.Max(j, mid);                     low = mid + 1;                 }                 else {                     high = mid - 1;                 }             }              // Index of the largest valid prefix sum             int index = (int)stk[j][1];              // Update dp[i] to reflect the maximum length of             // non-decreasing subarray ending at i             dp[i] = dp[index] + 1;              // Calculate the new value to be added to stk             long currLast                 = 2 * prefixSum[i] - prefixSum[index];              // Maintain the stack property by removing             // elements that do not satisfy the condition             while (stk[stk.Count - 1][0] >= currLast)                 stk.RemoveAt(stk.Count - 1);              // Add the new value and index to stk             stk.Add(new long[] { currLast, i });         }          // The result is the maximum length of         // non-decreasing subarray that can be obtained         return dp[n];     }      // Driver code to test the above function     public static void Main()     {         // Test case 1         List<int> nums1 = new List<int>{ 5, 1, 6, 6, 6 };         Console.WriteLine(FindMaximumLength(nums1));          // Test case 2         List<int> nums2             = new List<int>{ 5, 1, 6, 7, 7, 1, 6, 4, 5 };         Console.WriteLine(FindMaximumLength(nums2));     } } 
JavaScript
// Function to find the maximum length of a non-decreasing // array that can be made after applying operations function findMaximumLength(arr) {     // Length of the input array     const n = arr.length;      // prefixSum stores the prefix sums of the arr array     const prefixSum = new Array(n + 1).fill(0);      // dp stores the maximum length of a non-decreasing     // subarray ending at each index     const dp = new Array(n + 1).fill(0);      // Calculate prefix sums     for (let i = 1; i <= n; i++)         prefixSum[i] = prefixSum[i - 1] + arr[i - 1];      // stk stores pairs of {value, index} to maintain     // potential maximum lengths     const stk = [[0, 0]];      // Iterate over the array to find the maximum length     for (let i = 1; i <= n; i++) {         let low = 0, high = stk.length - 1;         let j = 0;          // Binary search to find the largest j such that         // prefixSum[j] <= prefixSum[i]         while (low <= high) {             const mid = low + Math.floor((high - low) / 2);              if (stk[mid][0] <= prefixSum[i]) {                 j = Math.max(j, mid);                 low = mid + 1;             } else {                 high = mid - 1;             }         }          // Index of the largest valid prefix sum         const index = stk[j][1];          // Update dp[i] to reflect the maximum length of         // non-decreasing subarray ending at i         dp[i] = dp[index] + 1;          // Calculate the new value to be added to stk         const currLast = 2 * prefixSum[i] - prefixSum[index];          // Maintain the stack property by removing elements         // that do not satisfy the condition         while (stk[stk.length - 1][0] >= currLast)             stk.pop();          // Add the new value and index to stk         stk.push([currLast, i]);     }      // The result is the maximum length of non-decreasing     // subarray that can be obtained     return dp[n]; }  // Driver code to test the above function // Test case 1 const nums1 = [5, 1, 6, 6, 6]; console.log(findMaximumLength(nums1));   // Test case 2 const nums2 = [5, 1, 6, 7, 7, 1, 6, 4, 5]; console.log(findMaximumLength(nums2)); // Expected output 

Output
4 6 

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)


Next Article
Maximize point to reduce Array by replacing Subarray with its sum

G

garg28harsh
Improve
Article Tags :
  • Greedy
  • Technical Scripter
  • DSA
  • Arrays
  • Technical Scripter 2022
  • subarray-sum
Practice Tags :
  • Arrays
  • Greedy

Similar Reads

  • Maximize point to reduce Array by replacing Subarray with its sum
    Given an array arr[] of size, N, the task is to maximize the score to reduce the array to a single element by replacing any subarray with its sum where the score of one such operation is the product of subarray length and the minimum value of that subarray. Examples:Input: N = 2, arr[] = {1, 5}Outpu
    15 min read
  • Maximize Array sum by replacing middle elements with min of Subarray corners
    Given an array A[] of length N. Then your task is to output the maximum sum that can be achieved by using the given operation at any number of times (possibly zero): Select a subarray, whose length is at least 3.Replace all the middle elements (Except the first and last) with a minimum of elements a
    7 min read
  • Minimum size Subarray with maximum sum in non-increasing order
    Given an array arr, the task is to find a subarray of the array elements whose sum is strictly greater than the rest of the elements. The size of the subarray should be minimum and the sum should be maximum and it must be in non-increasing order.Examples: Input: arr = [7, 6, 13, 12, 11] Output: 13 1
    6 min read
  • Maximize deletions by removing prefix and suffix of Array with same sum
    Given an array Arr[] of size N, the cost of removing ith element is Arr[i]. The task is to remove the maximum number of elements by removing the prefix and the suffix of the same length and having the same total cost. Examples: Input: Arr[] = {80, 90, 81, 80}Output: 2 Explanation: If we choose 80 fr
    10 min read
  • Find maximum sum by replacing the Subarray in given range
    Given an array arr[], the task is to find the maximum sum possible such that any subarray of the indices from [l, r] i.e all subarray elements from arr[l] to arr[r] can be replaced with |arr[l] - arr[r]| any number of times. Examples: Input: arr[] = { 9, 1}Output: 16Explanation: The subarray [l, r]
    9 min read
  • Maximum Subarray Sum possible by replacing an Array element by its Square
    Given an array a[] consisting of N integers, the task is to find the maximum subarray sum that can be obtained by replacing a single array element by its square. Examples: Input: a[] = {1, -5, 8, 12, -8} Output: 152 Explanation: Replacing 12 by 144, the subarray {8, 144} generates the maximum possib
    12 min read
  • Maximize the minimum array element by M subarray increments of size S
    Given an array arr[] of N integers and two integers S and M, the task is to maximize the minimum array element by incrementing any subarray of size S by 1, M number of times. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, S = 2, M = 3Output: 3Explanation:Below are the operations performed:Operation 1:
    10 min read
  • Maximum sum two non-overlapping subarrays of given size
    Given an array, we need to find two subarrays with a specific length K such that sum of these subarrays is maximum among all possible choices of subarrays. Examples: Input : arr[] = [2, 5, 1, 2, 7, 3, 0] K = 2 Output : 2 5 7 3 We can choose two arrays of maximum sum as [2, 5] and [7, 3], the sum of
    12 min read
  • Maximize the subarray sum by choosing M subarrays of size K
    Given an array arr containing N positive integers, and two integers K and M, the task is to calculate the maximum sum of M subarrays of size K. Example: Input: arr[] = {1, 2, 1, 2, 6, 7, 5, 1}, M = 3, K = 2Output: 33Explanation: The three chosen subarrays are [2, 6], [6, 7] and [7, 5] respectively.
    6 min read
  • Find an array of size N having exactly K subarrays with sum S
    Given three integers N, K and S, the task is to choose an array of size N such that there exists exactly K sub-arrays with sum S.Note: There can be many solution arrays to this problem.Examples: Input: N = 4, K = 2, S = 3 Output: 1 2 3 4 Explanation: One of the possible array is [ 1, 2, 3, 4 ] There
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences