The Wayback Machine - https://web.archive.org/web/20240907052348/https://www.geeksforgeeks.org/maximize-length-of-longest-subarray-consisting-of-same-elements-by-at-most-k-decrements/
Open In App

Maximize length of longest subarray consisting of same elements by at most K decrements

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[] of size N and an integer K, the task is to find the length of the longest subarray consisting of same elements that can be obtained by decrementing the array elements by 1 at most K times.

Example:

Input: arr[] = { 1, 2, 3 }, K = 1
Output: 2
Explanation:
Decrementing arr[0] by 1 modifies arr[] to { 1, 1, 3 }
The longest subarray with equal elements is { 1, 1 }.
Therefore, the required output is 2.

Input: arr[] = { 1, 7, 3, 4, 5, 6 }, K = 6
Output: 4

Approach: The problem can be solved using Segment tree and Binary Search technique. The idea is to use the following observations:

Total number of decrements operations required to make all array elements of the subarray { arr[start], …, arr[end] } equal
= (?(start, end)) – (end – start + 1) * (min_value)

where, start = index of the starting point of the subarray
end = index of end point of subarray
min_value = smallest value from index i to j
?(start, end) = sum of all elements from index i to j

Follow the steps below to solve the above problem:

  1. Initialize a segment tree to calculate the smallest element in a subarray of the array and a prefix sum array to calculate the sum elements of a subarray.
  2. Traverse the array, arr[]. For every ith element perform the following operations:
    • Initialize two variables say, start = i, end = N – 1 and apply binary search over the range [start, end] to check if the all the elements of the subarray { arr[start], …, arr[end] } can be made equal or not by decrementing at most K operations from the above observations.
    • If all the elements of the subarray { arr[start], …, arr[end] } can be made equal by decrementing at most K operations then update start = (start + end) / 2 + 1.
    • Otherwise, update end = (start + end) / 2 – 1
       
  3. Finally, print the length of the longest subarray obtained from the above operations.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to construct Segment Tree
// to return the minimum element in a range
int build(int tree[], int* A, int start,
          int end, int node)
{
    // If leaf nodes of
    // the tree are found
    if (start == end) {
  
        // Update the value in segment
        // tree from given array
        tree[node] = A[start];
  
        return tree[node];
    }
  
    // Divide left and right subtree
    int mid = (start + end) / 2;
  
    // Stores smallest element in
    // subarray { arr[start], arr[mid] }
    int X = build(tree, A, start, mid,
                  2 * node + 1);
  
    // Stores smallest element in
    // subarray { arr[mid + 1], arr[end] }
    int Y = build(tree, A, mid + 1,
                  end, 2 * node + 2);
  
    // Stores smallest element in
    // subarray { arr[start], arr[end] }
    return tree[node] = min(X, Y);
}
  
// Function to find the smallest
// element present in a subarray
int query(int tree[], int start, int end,
          int l, int r, int node)
{
    // If elements of the subarray
    // are not in the range [l, r]
    if (start > r || end < l)
        return INT_MAX;
  
    // If all the elements of the
    // subarray are in the range [l, r]
    if (start >= l && end <= r)
        return tree[node];
  
    // Divide tree into left
    // and right subtree
    int mid = (start + end) / 2;
  
    // Stores smallest element
    // in left subtree
    int X = query(tree, start, mid, l,
                  r, 2 * node + 1);
  
    // Stores smallest element in
    // right subtree
    int Y = query(tree, mid + 1, end, l,
                  r, 2 * node + 2);
  
    return min(X, Y);
}
  
// Function that find length of longest
// subarray with all equal elements in
// atmost K decrements
int longestSubArray(int* A, int N, int K)
{
    // Stores length of longest subarray
    // with all equal elements in atmost
    // K decrements.
    int res = 1;
  
    // Store the prefix sum array
    int preSum[N + 1];
  
    // Calculate the prefix sum array
    preSum[0] = A[0];
    for (int i = 0; i < N; i++)
        preSum[i + 1] = preSum[i] + A[i];
  
    int tree[4 * N + 5];
  
    // Build the segment tree
    // for range min query
    build(tree, A, 0, N - 1, 0);
  
    // Traverse the array
    for (int i = 0; i < N; i++) {
  
        // Stores start index
        // of the subarray
        int start = i;
  
        // Stores end index
        // of the subarray
        int end = N - 1;
  
        int mid;
  
        // Stores end index of
        // the longest subarray
        int max_index = i;
  
        // Performing the binary search
        // to find the endpoint
        // for the selected range
        while (start <= end) {
  
            // Find the mid for binary search
            mid = (start + end) / 2;
  
            // Find the smallest element in
            // range [i, mid] using Segment Tree
            int min_element
                = query(tree, 0, N - 1, i, mid, 0);
  
            // Stores total sum of subarray
            // after K decrements
            int expected_sum
                = (mid - i + 1) * min_element;
  
            // Stores sum of elements of
            // subarray before K decrements
            int actual_sum
                = preSum[mid + 1] - preSum[i];
  
            // If subarray found with
            // all equal elements
            if (actual_sum - expected_sum <= K) {
  
                // Update start
                start = mid + 1;
  
                // Update max_index
                max_index = max(max_index, mid);
            }
  
            // If false, it means that
            // the selected range is invalid
            else {
  
                // Update end
                end = mid - 1;
            }
        }
  
        // Store the length of longest subarray
        res = max(res, max_index - i + 1);
    }
  
    // Return result
    return res;
}
  
// Driver Code
int main()
{
    int arr[] = { 1, 7, 3, 4, 5, 6 };
    int k = 6;
    int n = 6;
    cout << longestSubArray(arr, n, k);
  
    return 0;
}


Java




// Java program to implement 
// the above approach 
import java.util.*;
   
class GFG{
  
// Function to construct Segment Tree
// to return the minimum element in a range
static int build(int tree[], int[] A, int start,
                 int end, int node)
{
      
    // If leaf nodes of
    // the tree are found
    if (start == end) 
    {
          
        // Update the value in segment
        // tree from given array
        tree[node] = A[start];
   
        return tree[node];
    }
   
    // Divide left and right subtree
    int mid = (start + end) / 2;
   
    // Stores smallest element in
    // subarray { arr[start], arr[mid] }
    int X = build(tree, A, start, mid,
                  2 * node + 1);
   
    // Stores smallest element in
    // subarray { arr[mid + 1], arr[end] }
    int Y = build(tree, A, mid + 1,
                 end, 2 * node + 2);
   
    // Stores smallest element in
    // subarray { arr[start], arr[end] }
    return (tree[node] = Math.min(X, Y));
}
   
// Function to find the smallest
// element present in a subarray
static int query(int tree[], int start, int end,
                 int l, int r, int node)
{
      
    // If elements of the subarray
    // are not in the range [l, r]
    if (start > r || end < l)
        return Integer.MAX_VALUE;
   
    // If all the elements of the
    // subarray are in the range [l, r]
    if (start >= l && end <= r)
        return tree[node];
   
    // Divide tree into left
    // and right subtree
    int mid = (start + end) / 2;
   
    // Stores smallest element
    // in left subtree
    int X = query(tree, start, mid, l,
                  r, 2 * node + 1);
   
    // Stores smallest element in
    // right subtree
    int Y = query(tree, mid + 1, end, l,
                  r, 2 * node + 2);
   
    return Math.min(X, Y);
}
   
// Function that find length of longest
// subarray with all equal elements in
// atmost K decrements
static int longestSubArray(int[] A, int N, int K)
{
      
    // Stores length of longest subarray
    // with all equal elements in atmost
    // K decrements.
    int res = 1;
   
    // Store the prefix sum array
    int preSum[] = new int[N + 1];
   
    // Calculate the prefix sum array
    preSum[0] = A[0];
    for(int i = 0; i < N; i++)
        preSum[i + 1] = preSum[i] + A[i];
   
    int tree[] = new int[4 * N + 5];
   
    // Build the segment tree
    // for range min query
    build(tree, A, 0, N - 1, 0);
   
    // Traverse the array
    for(int i = 0; i < N; i++) 
    {
          
        // Stores start index
        // of the subarray
        int start = i;
   
        // Stores end index
        // of the subarray
        int end = N - 1;
   
        int mid;
   
        // Stores end index of
        // the longest subarray
        int max_index = i;
   
        // Performing the binary search
        // to find the endpoint
        // for the selected range
        while (start <= end)
        {
              
            // Find the mid for binary search
            mid = (start + end) / 2;
   
            // Find the smallest element in
            // range [i, mid] using Segment Tree
            int min_element = query(tree, 0, N - 1,
                                    i, mid, 0);
   
            // Stores total sum of subarray
            // after K decrements
            int expected_sum = (mid - i + 1) *
                                min_element;
   
            // Stores sum of elements of
            // subarray before K decrements
            int actual_sum = preSum[mid + 1] - 
                             preSum[i];
   
            // If subarray found with
            // all equal elements
            if (actual_sum - expected_sum <= K) 
            {
                  
                // Update start
                start = mid + 1;
   
                // Update max_index
                max_index = Math.max(max_index, mid);
            }
   
            // If false, it means that
            // the selected range is invalid
            else 
            {
                  
                // Update end
                end = mid - 1;
            }
        }
   
        // Store the length of longest subarray
        res = Math.max(res, max_index - i + 1);
    }
   
    // Return result
    return res;
}
   
// Driver Code
static public void main(String args[])
{
    int arr[] = { 1, 7, 3, 4, 5, 6 };
    int k = 6;
    int n = 6;
      
    System.out.print(longestSubArray(arr, n, k));
}
}
  
// This code is contributed by sanjoy_62


Python3




# Python3 program to implement
# the above approach
import sys
  
# Function to construct Segment Tree
# to return the minimum element in a range
def build(tree, A, start, end, node):
      
    # If leaf nodes of
    # the tree are found
    if (start == end):
          
        # Update the value in segment
        # tree from given array
        tree[node] = A[start]
   
        return tree[node]
      
    # Divide left and right subtree
    mid = (int)((start + end) / 2)
   
    # Stores smallest element in
    # subarray : arr[start], arr[mid] 
    X = build(tree, A, start, mid,
              2 * node + 1)
  
    # Stores smallest element in
    # subarray : arr[mid + 1], arr[end] 
    Y = build(tree, A, mid + 1,
             end, 2 * node + 2)
   
    # Stores smallest element in
    # subarray : arr[start], arr[end] 
    return (tree[node] == min(X, Y))
  
# Function to find the smallest
# element present in a subarray
def query(tree, start, end, l, r, node):
                
    # If elements of the subarray
    # are not in the range [l, r]
    if (start > r or end < l) :
        return sys.maxsize
   
    # If all the elements of the
    # subarray are in the range [l, r]
    if (start >= l and end <= r):
        return tree[node]
   
    # Divide tree into left
    # and right subtree
    mid = (int)((start + end) / 2)
   
    # Stores smallest element
    # in left subtree
    X = query(tree, start, mid, l,
              r, 2 * node + 1)
   
    # Stores smallest element in
    # right subtree
    Y = query(tree, mid + 1, end, l,
            r, 2 * node + 2)
   
    return min(X, Y)
  
# Function that find length of longest
# subarray with all equal elements in
# atmost K decrements
def longestSubArray(A, N, K):
      
    # Stores length of longest subarray
    # with all equal elements in atmost
    # K decrements.
    res = 1
   
    # Store the prefix sum array
    preSum = [0] * (N + 1)
   
    # Calculate the prefix sum array
    preSum[0] = A[0]
    for i in range(N):
        preSum[i + 1] = preSum[i] + A[i]
   
    tree = [0] * (4 * N + 5)
   
    # Build the segment tree
    # for range min query
    build(tree, A, 0, N - 1, 0)
   
    # Traverse the array
    for i in range(N):
   
        # Stores start index
        # of the subarray
        start = i
   
        # Stores end index
        # of the subarray
        end = N - 1
   
        # Stores end index of
        # the longest subarray
        max_index = i
   
        # Performing the binary search
        # to find the endpoint
        # for the selected range
        while (start <= end):
   
            # Find the mid for binary search
            mid = (int)((start + end) / 2)
   
            # Find the smallest element in
            # range [i, mid] using Segment Tree
            min_element = query(tree, 0, N - 1, i, mid, 0)
   
            # Stores total sum of subarray
            # after K decrements
            expected_sum = (mid - i + 1) * min_element
   
            # Stores sum of elements of
            # subarray before K decrements
            actual_sum = preSum[mid + 1] - preSum[i]
   
            # If subarray found with
            # all equal elements
            if (actual_sum - expected_sum <= K):
                  
                # Update start
                start = mid + 1
   
                # Update max_index
                max_index = max(max_index, mid)
              
            # If false, it means that
            # the selected range is invalid
            else:
   
                # Update end
                end = mid - 1
              
        # Store the length of longest subarray
        res = max(res, max_index - i + 2)
  
    # Return result
    return res
  
# Driver Code
arr = [ 1, 7, 3, 4, 5, 6 ]
k = 6
n = 6
  
print(longestSubArray(arr, n, k))
  
# This code is contributed by splevel62


C#




// C# program to implement 
// the above approach 
using System;
   
class GFG{
       
// Function to construct Segment Tree
// to return the minimum element in a range
static int build(int[] tree, int[] A, int start,
                 int end, int node)
{
      
    // If leaf nodes of
    // the tree are found
    if (start == end) 
    {
          
        // Update the value in segment
        // tree from given array
        tree[node] = A[start];
    
        return tree[node];
    }
    
    // Divide left and right subtree
    int mid = (start + end) / 2;
    
    // Stores smallest element in
    // subarray { arr[start], arr[mid] }
    int X = build(tree, A, start, mid,
                  2 * node + 1);
    
    // Stores smallest element in
    // subarray { arr[mid + 1], arr[end] }
    int Y = build(tree, A, mid + 1,
                  end, 2 * node + 2);
    
    // Stores smallest element in
    // subarray { arr[start], arr[end] }
    return (tree[node] = Math.Min(X, Y));
}
    
// Function to find the smallest
// element present in a subarray
static int query(int[] tree, int start, int end,
                 int l, int r, int node)
{
       
    // If elements of the subarray
    // are not in the range [l, r]
    if (start > r || end < l)
        return Int32.MaxValue;
    
    // If all the elements of the
    // subarray are in the range [l, r]
    if (start >= l && end <= r)
        return tree[node];
    
    // Divide tree into left
    // and right subtree
    int mid = (start + end) / 2;
    
    // Stores smallest element
    // in left subtree
    int X = query(tree, start, mid, l,
                  r, 2 * node + 1);
    
    // Stores smallest element in
    // right subtree
    int Y = query(tree, mid + 1, end, l,
                  r, 2 * node + 2);
    
    return Math.Min(X, Y);
}
    
// Function that find length of longest
// subarray with all equal elements in
// atmost K decrements
static int longestSubArray(int[] A, int N, int K)
{
       
    // Stores length of longest subarray
    // with all equal elements in atmost
    // K decrements.
    int res = 1;
    
    // Store the prefix sum array
    int[] preSum = new int[N + 1];
    
    // Calculate the prefix sum array
    preSum[0] = A[0];
    for(int i = 0; i < N; i++)
        preSum[i + 1] = preSum[i] + A[i];
    
    int[] tree = new int[4 * N + 5];
    
    // Build the segment tree
    // for range min query
    build(tree, A, 0, N - 1, 0);
    
    // Traverse the array
    for(int i = 0; i < N; i++) 
    {
           
        // Stores start index
        // of the subarray
        int start = i;
    
        // Stores end index
        // of the subarray
        int end = N - 1;
    
        int mid;
    
        // Stores end index of
        // the longest subarray
        int max_index = i;
    
        // Performing the binary search
        // to find the endpoint
        // for the selected range
        while (start <= end)
        {
               
            // Find the mid for binary search
            mid = (start + end) / 2;
    
            // Find the smallest element in
            // range [i, mid] using Segment Tree
            int min_element = query(tree, 0, N - 1,
                                    i, mid, 0);
    
            // Stores total sum of subarray
            // after K decrements
            int expected_sum = (mid - i + 1) *
                                min_element;
    
            // Stores sum of elements of
            // subarray before K decrements
            int actual_sum = preSum[mid + 1] - 
                             preSum[i];
    
            // If subarray found with
            // all equal elements
            if (actual_sum - expected_sum <= K) 
            {
                   
                // Update start
                start = mid + 1;
    
                // Update max_index
                max_index = Math.Max(max_index, mid);
            }
    
            // If false, it means that
            // the selected range is invalid
            else
            {
                   
                // Update end
                end = mid - 1;
            }
        }
    
        // Store the length of longest subarray
        res = Math.Max(res, max_index - i + 1);
    }
    
    // Return result
    return res;
}
   
// Driver Code
static void Main()
{
    int[] arr = { 1, 7, 3, 4, 5, 6 };
    int k = 6;
    int n = 6;
       
    Console.WriteLine(longestSubArray(arr, n, k));
}
}
  
// This code is contributed by susmitakundugoaldanga


Javascript




<script>
  
// JavaScript program to implement
// the above approach
  
// Function to construct Segment Tree
// to return the minimum element in a range
function build(tree,A, start,end, node)
{
    // If leaf nodes of
    // the tree are found
    if (start == end) {
  
        // Update the value in segment
        // tree from given array
        tree[node] = A[start];
  
        return tree[node];
    }
  
    // Divide left and right subtree
    let mid = Math.floor((start + end) / 2);
  
    // Stores smallest element in
    // subarray { arr[start], arr[mid] }
    let X = build(tree, A, start, mid,
                2 * node + 1);
  
    // Stores smallest element in
    // subarray { arr[mid + 1], arr[end] }
    let Y = build(tree, A, mid + 1,
                end, 2 * node + 2);
  
    // Stores smallest element in
    // subarray { arr[start], arr[end] }
    return tree[node] = Math.min(X, Y);
}
  
// Function to find the smallest
// element present in a subarray
function query(tree,start, end,l, r, node)
{
    // If elements of the subarray
    // are not in the range [l, r]
    if (start > r || end < l)
        return Number.MAX_VALUE;
  
    // If all the elements of the
    // subarray are in the range [l, r]
    if (start >= l && end <= r)
        return tree[node];
  
    // Divide tree into left
    // and right subtree
    let mid = Math.floor((start + end) / 2);
  
    // Stores smallest element
    // in left subtree
    let X = query(tree, start, mid, l,
                r, 2 * node + 1);
  
    // Stores smallest element in
    // right subtree
    let Y = query(tree, mid + 1, end, l,
                r, 2 * node + 2);
  
    return Math.min(X, Y);
}
  
// Function that find length of longest
// subarray with all equal elements in
// atmost K decrements
function longestSubArray(A,N,K)
{
    // Stores length of longest subarray
    // with all equal elements in atmost
    // K decrements.
    let res = 1;
  
    // Store the prefix sum array
    let preSum = new Array(N + 1);
  
    // Calculate the prefix sum array
    preSum[0] = A[0];
    for (let i = 0; i < N; i++)
        preSum[i + 1] = preSum[i] + A[i];
  
    let tree = new Array(4 * N + 5);
  
    // Build the segment tree
    // for range min query
    build(tree, A, 0, N - 1, 0);
  
    // Traverse the array
    for (let i = 0; i < N; i++) {
  
        // Stores start index
        // of the subarray
        let start = i;
  
        // Stores end index
        // of the subarray
        let end = N - 1;
  
        let mid;
  
        // Stores end index of
        // the longest subarray
        let max_index = i;
  
        // Performing the binary search
        // to find the endpoint
        // for the selected range
        while (start <= end) {
  
            // Find the mid for binary search
            mid = Math.floor((start + end) / 2);
  
            // Find the smallest element in
            // range [i, mid] using Segment Tree
            let min_element
                = query(tree, 0, N - 1, i, mid, 0);
  
            // Stores total sum of subarray
            // after K decrements
            let expected_sum
                = (mid - i + 1) * min_element;
  
            // Stores sum of elements of
            // subarray before K decrements
            let actual_sum
                = preSum[mid + 1] - preSum[i];
  
            // If subarray found with
            // all equal elements
            if (actual_sum - expected_sum <= K) {
  
                // Update start
                start = mid + 1;
  
                // Update max_index
                max_index = Math.max(max_index, mid);
            }
  
            // If false, it means that
            // the selected range is invalid
            else {
  
                // Update end
                end = mid - 1;
            }
        }
  
        // Store the length of longest subarray
        res = Math.max(res, max_index - i + 1);
    }
  
    // Return result
    return res;
}
  
// Driver Code
let arr = [ 1, 7, 3, 4, 5, 6 ];
let k = 6;
let n = 6;
document.write(longestSubArray(arr, n, k),"</br>");
  
// This code is contributed by shinjanpatra
  
</script>


Output:

4

 

Time Complexity: O(N * (log(N))2)
Auxiliary Space: O(N)

Related Topic: Segment Tree



Previous Article
Next Article

Similar Reads

Maximum sum of K-length subarray consisting of same number of distinct elements as the given array
Given an array arr[] consisting of N integers and an integer K, the task is to find a subarray of size K with maximum sum and count of distinct elements same as that of the original array. Examples: Input: arr[] = {7, 7, 2, 4, 2, 7, 4, 6, 6, 6}, K = 6Output: 31Explanation: The given array consists of 4 distinct elements, i.e. {2, 4, 6, 7}. The suba
15+ min read
Maximize absolute difference between X and Y by at most N decrements
Given five integers X, Y, A, B, and N, the task is to find the maximum possible absolute difference between X and Y by performing the following operations exactly N times: Decrement the value of X by 1 up to A.Decrement the value of Y by 1 up to B. Note: The value of (X - A + Y - B) must be greater than or equal to N Examples: Input: X = 12, Y = 8,
9 min read
Query to find length of the longest subarray consisting only of 1s
Given a binary array arr[] of size N and a 2D array Q[][] containing K queries of the following two types: 1 : Print the length of the longest subarray consisting of 1s only.2 X : Flip the element at the Xth index (1-based indexing) i.e change the element to '1' if the current element is '0' and vice versa. Examples: Input: N = 10, arr[] = {1, 1, 0
15+ min read
Length of longest subarray consisting only of 1s
Given an array arr[] of size N, consisting of binary values, the task is to find the longest non-empty subarray consisting only of 1s after removal of a single array element. Examples: Input: arr[] = {1, 1, 1}Output: 2 Input: arr[] = {0, 0, 0}Output: 0 Approach: Follow the steps below to solve the problem: Initialize three variables, newLen = 0, pr
6 min read
Maximum length of subarray consisting of same type of element on both halves of sub-array
Given an array arr[] of N integers, the task is to find the maximum length of sub-array consisting of the same type of element on both halves of the sub-array. Also, the elements on both halves differ from each other. Examples: Input: arr[] = {2, 3, 4, 4, 5, 5, 6, 7, 8, 10}Output: 4Explanation:{2, 3}, {3, 4}, {4, 4, 5, 5}, {5, 6}, etc, are the vali
8 min read
Maximize subarray sum by inverting sign of elements of any subarray at most twice
Given an array A of size n, find the maximum subarray sum after applying the given operation at most two times. In one operation, choose any two indices i and j and invert sign of all the elements from index i to index j, i.e, all positive elements in the range i to j become negative and all negative elements become positive. Examples: Input: A[] =
10 min read
Longest Subarray consisting of unique elements from an Array
Given an array arr[] consisting of N integers, the task is to find the largest subarray consisting of unique elements only. Examples: Input: arr[] = {1, 2, 3, 4, 5, 1, 2, 3} Output: 5 Explanation: One possible subarray is {1, 2, 3, 4, 5}. Input: arr[]={1, 2, 4, 4, 5, 6, 7, 8, 3, 4, 5, 3, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4} Output: 8 Explanation: Only pos
5 min read
Maximize length of subarray of equal elements by performing at most K increment operations
Given an array A[] consisting of N integers and an integer K, the task is to maximize the length of the subarray having equal elements after performing at most K increments by 1 on array elements. Note: Same array element can be incremented more than once. Examples: Input: A[] = {2, 4, 8, 5, 9, 6}, K = 6Output: 3Explanation:Subarray [8, 5, 9] can b
8 min read
Maximize length of subarray having equal elements by adding at most K
Given an array arr[] consisting of N positive integers and an integer K, which represents the maximum number that can be added to the array elements. The task is to maximize the length of the longest possible subarray of equal elements by adding at most K. Examples: Input: arr[] = {3, 0, 2, 2, 1}, k = 3Output: 4Explanation: Step 1: Adding 2 to arr[
9 min read
Maximize pair decrements required to reduce all array elements except one to 0
Given an array arr[] consisting of N distinct elements, the task is to find the maximum number of pairs required to be decreased by 1 in each step, such that N - 1 array elements are reduced to 0 and the remaining array element is a non-negative integer. Examples: Input: arr[] = {1, 2, 3}Output: 3Explanation: Decrease arr[1] and arr[2] by 1 modifie
13 min read
Minimize subarray increments/decrements required to reduce all array elements to 0
Given an array arr[], select any subarray and apply any one of the below operations on each element of the subarray: Increment by oneDecrement by one The task is to print the minimum number of above-mentioned increment/decrement operations required to reduce all array elements to 0. Examples: Input: arr[] = {1, 3, 4, 1}Output: 4Explanation: Optimal
5 min read
Minimum decrements to make an Array at most 0 such that all array elements are cyclically decremented after a number is reduced to 0
Given a circular array arr[] of N integers and an array cost[], the task is to calculate the minimum number of operations required to make all elements of the array equal to 0, where at each operation decrement the value of an index i by 1. If the value of an index becomes 0, decrement the value of arr[i+1] by cost[i], decrement the value of arr[i
6 min read
Length of Longest Subarray with same elements in atmost K increments
Given an integer array arr and a number K, the task is to find the length of the longest subarray such that all the elements in this subarray can be made the same in atmost K increments. Examples: Input: arr[] = {2, 0, 4, 6, 7}, K = 6 Output: 3 The longest subarray is {2, 0, 4} which can be made as {4, 4, 4} with total increments = 6 ( ? K ) Input:
15+ min read
Minimize cost of increments or decrements such that same indexed elements become multiple of each other
Given two arrays A[] and B[] consisting of N integers, the task is to minimize the total cost of incrementing or decrementing array elements by 1 such that for every ith element, either A[i] is a multiple of B[i] or vice-versa. Examples: Input: A[] = {3, 6, 3}, B[] = {4, 8, 13}Output: 4Explanation:Incrementing A[0] by 1 (3 + 1 = 4) makes it multipl
6 min read
Minimize decrements to make each Array elements same or 0
Given an array arr[] consisting of N positive integers. In one operation any number of the array can be decremented by 1. The task is to find the minimum number of operations required to make all of the elements equal or 0. Examples: Input: arr[] = {4, 1, 6, 6}Output: 5Explanation: Remove 1 from arr{1}, array becomes, {4, 0, 6, 6}, makes 1 operatio
5 min read
Length of smallest subarray consisting of all occurrences of all maximum occurring elements
Given an array arr[] of size N, The task is to find the length of the smallest subarray consisting of all the occurrences of maximum occurring elementsExamples: Input: arr[] = {1, 2, 1, 3, 2}Output: 5Explanation: Elements with maximum frequency (=2) are 1 &amp; 2. Therefore, the length of smallest subarray consisting of all the occurrences of 1 and
6 min read
Length of longest subsequence consisting of distinct adjacent elements
Given an array arr[], the task is to find the length of the longest subsequence of the array arr[] such that all adjacent elements in the subsequence are different. Examples: Input: arr[] = {4, 2, 3, 4, 3}Output: 5Explanation:The longest subsequence where no two adjacent elements are equal is {4, 2, 3, 4, 3}. Length of the subsequence is 5. Input:
5 min read
Length of the longest subsequence consisting of distinct elements
Given an array arr[] of size N, the task is to find the length of the longest subsequence consisting of distinct elements only. Examples: Input: arr[] = {1, 1, 2, 2, 2, 3, 3} Output: 3 Explanation: The longest subsequence with distinct elements is {1, 2, 3} Input: arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 } Output: 5 Naive Approach: The simplest approach is
4 min read
Largest element in the longest Subarray consisting of only Even or only Odd numbers
Given an array arr[] of size N, the task is to find the largest element in the longest subarray consisting only of even numbers or odd numbers. Examples: Input: arr[] = { 2, 4, 6, 9, 10, 11 } Output: 6 Explanation: The longest subarray consisting of only even or odd numbers is { arr[0], arr[1], arr[2] }. Since the largest element of the subarray is
15+ min read
Maximize product of min value of subarray and sum of subarray over all subarrays of length K
Given an array arr[] of N integers, the task is to find the maximum possible value of (min * sum) among all possible subarrays having K elements, where min denotes the smallest integer of the subarray and sum denotes the sum of all elements of the subarray. Example: Input: arr[] = {1, 2, 3, 2}, K = 3Output: 14Explanation: For the subarray {2, 3, 2}
7 min read
Maximize length of Non-Decreasing Subsequence by reversing at most one Subarray
Given a binary array arr[], the task is to find the maximum possible length of non-decreasing subsequence that can be generated by reversing a subarray at most once. Examples: Input: arr[] = {0, 1, 0, 1} Output: 4 Explanation: After reversing the subarray from index [2, 3], the array modifies to {0, 0, 1, 1}. Hence, the longest non-decreasing subse
9 min read
Maximize GCD of an array by increments or decrements by K
Given an array arr[] consisting of N positive integers and a positive integer K, the task is to maximize the GCD of the array arr[] by either increasing or decreasing any array element by K. Examples: Input: arr[] = {3, 9, 15, 24}, K = 1Output: 4Explanation:Perform the following operations on the array arr[]:Increment arr[0] by 1. Therefore, arr[]
15+ min read
Maximize minimum array element possible by exactly K decrements
Given an array arr[] consisting of N integers and an integer K, the task is to maximize the minimum element of the array after decrementing array elements exactly K number of times. Examples: Input: arr[] = {2, 4, 4}, K = 3 Output: 2Explanation:One of the possible way is: Decrement arr[2] by 1. The array modifies to {2, 4, 3}.Decrement arr[1] by 1.
7 min read
Length of Longest Subarray having at Most K Frequency
Given an integer array arr[]and an integer K, the task is to find the length of the longest subarray such that the frequency of each element is less than or equal to K. Examples: Input: arr[] = {10, 20, 30, 10, 20, 30, 10, 20}, K = 2Output: 6Explanation: The longest possible subarray is {10, 20, 30, 10, 20, 30} since the values 10, 20 and 30 occur
5 min read
Maximize length of subsequence consisting of single distinct character possible by K increments in a string
Given a string S consisting of lowercase characters and an integer K, the task is to find the maximum length of a subsequence consisting of a single distinct character possible by incrementing at most K characters. Examples: Input: S = "acscbcca" K = 1Output: 5Explanation: Incrementing the character S[4] from 'b' to 'c', modifies the string to "acs
7 min read
Minimize positive product of two given numbers by at most N decrements
Given three integers X, Y, and N, the task is to find the minimum possible positive product of X and Y that can be obtained by decreasing either the value of X or Y by 1 at most N times. Examples: Input: X = 5, Y= 6, N = 4Output: 6Explanation:Decrease the value of X by 4, X = 5 - 4 = 1 and Y = 6.Therefore, the minimized product = X * Y = 1 * 6 = 6
6 min read
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Length of longest subarray in which elements greater than K are more than elements not greater than K
Given an array arr[] of length N. The task is to find the length of the longest subarray in which there are more greater (than a given number K) elements than elements less than or equal to K.Examples: Input : N = 5, K = 2, arr[]={ 1, 2, 3, 4, 1 } Output : 3 The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, and there is no subarray o
3 min read
Length of longest subsequence consisting of Non-Deficient Numbers
Given an array arr[] consisting of N natural numbers, the task is to find the length of the longest subsequence from the array which does not contain any deficient numbers. Examples: Input: arr[] = {13, 55, 240, 32, 24, 27, 56, 80, 100, 330, 89}Output: 6 Explanation:Array elements which are not deficient numbers are {240, 24, 56, 80, 100, 330}Divis
8 min read
Length of the longest substring consisting only of vowels in non-increasing order
Given a string S of size N consisting of lowercase alphabets, the task is to print the length of the longest substring consisting only of vowels sorted in non-increasing order. Examples: Input: S = "ueiaoaeiouuoiea"Output: 6Explanation: The only substring which consists only of vowels in non-increasing order, is the substring {S[9], S[15]}, which i
10 min read