The Wayback Machine - https://web.archive.org/web/20240818163946/https://www.geeksforgeeks.org/maximum-subarray-size-subarrays-size-sum-less-k/
Open In App

Maximum subarray size, such that all subarrays of that size have sum less than k

Last Updated : 10 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have the sum of elements less than or equals to k.

Examples : 

Input : arr[] = {1, 2, 3, 4} and k = 8. Output : 2 Sum of subarrays of size 1: 1, 2, 3, 4. Sum of subarrays of size 2: 3, 5, 7. Sum of subarrays of size 3: 6, 9. Sum of subarrays of size 4: 10. So, maximum subarray size such that all subarrays of that size have the sum of elements less than 8 is 2. Input : arr[] = {1, 2, 10, 4} and k = 8. Output : -1 There is an array element with value greater than k, so subarray sum cannot be less than k. Input : arr[] = {1, 2, 10, 4} and K = 14 Output : 2

Naive Approach: Firstly, the required subarray size must lie between 1 to n. Now, since all the array elements are positive integers, we can say that the prefix sum of any subarray shall be strictly increasing. Thus, we can say that 

if arr[i] + arr[i + 1] + ..... + arr[j - 1] + arr[j] <= K
then arr[i] + arr[i + 1] + ..... + arr[j - 1] <= K, as arr[j] is a positive integer.
  • Perform Binary Search over the range 1 to n and find the highest subarray size such that all the subarrays of that size have the sum of elements less than or equals to k.

Implementation:

C++
// C++ program to find maximum 
// subarray size, such that all 
// subarrays of that size have 
// sum less than K.
#include<bits/stdc++.h>
using namespace std;

// Search for the maximum length of 
// required subarray.
int bsearch(int prefixsum[], int n, 
                             int k)
{
    // Initialize result
    int ans = -1; 

    // Do Binary Search for largest 
    // subarray size 
    int left = 1, right = n;
    while (left <= right)
    {
        int mid = (left + right) / 2;

        // Check for all subarrays after mid
        int i;
        for (i = mid; i <= n; i++)
        {
            // Checking if all the subarrays
            //  of a size less than k.
            if (prefixsum[i] - prefixsum[i - mid] > k)
                break;
        }

        // All subarrays of size mid have 
        // sum less than or equal to k
        if (i == n + 1)
        {
            left = mid + 1;
            ans = mid;
        }

        // We found a subarray of size mid 
        // with sum greater than k
        else
            right = mid - 1;
    }
    return ans;
}

// Return the maximum subarray size,
// such that all subarray of that size
// have sum less than K.
int maxSize(int arr[], int n, int k)
{
    // Initialize prefix sum array as 0.
    int prefixsum[n + 1];
    memset(prefixsum, 0, sizeof(prefixsum));

    // Finding prefix sum of the array.
    for (int i = 0; i < n; i++)
        prefixsum[i + 1] = prefixsum[i] + 
                           arr[i];

    return bsearch(prefixsum, n, k);
}

// Driver code
int main()
{
    int arr[] = {1, 2, 10, 4};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 14;
    cout << maxSize(arr, n, k) << endl;
    return 0;
}
Java
// Java program to find maximum 
// subarray size, such that all 
// subarrays of that size have
// sum less than K.
import java.util.Arrays;

class GFG 
{
    
    // Search for the maximum length 
    // of required subarray.
    static int bsearch(int prefixsum[], 
                       int n, int k)
    {
        // Initialize result
        int ans = -1; 

        // Do Binary Search for largest 
        // subarray size
        int left = 1, right = n;
        
        while (left <= right) 
        {
            int mid = (left + right) / 2;

            // Check for all subarrays after mid
            int i;
            for (i = mid; i <= n; i++) 
            {
                
                // Checking if all the subarrays 
                // of a size is less than k.
                if (prefixsum[i] - prefixsum[i - mid] > k)
                    break;
            }

            // All subarrays of size mid have 
            // sum less than or equal to k
            if (i == n + 1)
            {
                left = mid + 1;
                ans = mid;
            }

            // We found a subarray of size mid 
            // with sum greater than k
            else
                right = mid - 1;
        }

        return ans;
    }

    // Return the maximum subarray size, such 
    // that all subarray of that size have 
    // sum less than K.
    static int maxSize(int arr[], int n, int k)
    {
        
        // Initialize prefix sum array as 0.
        int prefixsum[] = new int[n + 1];
        Arrays.fill(prefixsum, 0);

        // Finding prefix sum of the array.
        for (int i = 0; i < n; i++)
            prefixsum[i + 1] = prefixsum[i] + arr[i];

        return bsearch(prefixsum, n, k);
    }
    
    // Driver code
    public static void main(String arg[])
    {
        int arr[] = { 1, 2, 10, 4 };
        int n = arr.length;
        int k = 14;
        System.out.println(maxSize(arr, n, k));
    }
}

// This code is contributed by Anant Agarwal.
Python3
# Python3 program to find maximum 
# subarray size, such that all 
# subarrays of that size have
# sum less than K.

# Search for the maximum length of 
# required subarray.
def bsearch(prefixsum, n, k):

    # Initialize result
    # Do Binary Search for largest
    # subarray size
    ans, left, right = -1, 1, n

    while (left <= right):

        # Check for all subarrays after mid
        mid = (left + right)//2

        for i in range(mid, n + 1):

            # Checking if all the subarray of 
            # a size is less than k.
            if (prefixsum[i] - prefixsum[i - mid] > k):
                i = i - 1
                break
        i = i + 1
        if (i == n + 1):
            left = mid + 1
            ans = mid
        # We found a subarray of size mid with sum
        # greater than k
        else:
            right = mid - 1

    return ans;

# Return the maximum subarray size, such 
# that all subarray of that size have 
# sum less than K.
def maxSize(arr, n, k):
    prefixsum = [0 for x in range(n + 1)]
    
    # Finding prefix sum of the array.
    for i in range(n):
        prefixsum[i + 1] = prefixsum[i] + arr[i]

    return bsearch(prefixsum, n, k);

# Driver Code
arr = [ 1, 2, 10, 4 ]
n = len(arr)
k = 14
print (maxSize(arr, n, k))

# This code is contributed by Afzal
C#
// C# program to find maximum 
// subarray size, such that all 
// subarrays of that size have
// sum less than K.
using System;

class GFG {
    
    // Search for the maximum length 
    // of required subarray.
    static int bsearch(int []prefixsum, 
                          int n, int k)
    {
        
        // Initialize result
        int ans = -1; 

        // Do Binary Search for 
        // largest subarray size
        int left = 1, right = n;
        
        while (left <= right) 
        {
            int mid = (left + right) / 2;

            // Check for all subarrays 
            // after mid
            int i;
            for (i = mid; i <= n; i++) 
            {
                
                // Checking if all the 
                // subarrays of a size is
                // less than k.
                if (prefixsum[i] - 
                     prefixsum[i - mid] > k)
                    break;
            }

            // All subarrays of size mid have 
            // sum less than or equal to k
            if (i == n + 1)
            {
                left = mid + 1;
                ans = mid;
            }

            // We found a subarray of size mid 
            // with sum greater than k
            else
                right = mid - 1;
        }

        return ans;
    }

    // Return the maximum subarray size, such 
    // that all subarray of that size have 
    // sum less than K.
    static int maxSize(int []arr, int n, int k)
    {
        
        // Initialize prefix sum array as 0.
        int []prefixsum = new int[n + 1];
        for(int i=0;i<n+1;i++)
        prefixsum[i]=0;
        

        // Finding prefix sum of the array.
        for (int i = 0; i < n; i++)
            prefixsum[i + 1] = prefixsum[i]
                                     + arr[i];

        return bsearch(prefixsum, n, k);
    }
    
    // Driver code
    public static void Main()
    {
        int []arr = { 1, 2, 10, 4 };
        int n = arr.Length;
        int k = 14;
        
        Console.Write(maxSize(arr, n, k));
    }
}

// This code is contributed by nitin mittal.
JavaScript
<script>

// javascript program to find maximum 
// subarray size, such that all 
// subarrays of that size have
// sum less than K.

    // Search for the maximum length
    // of required subarray.
    function bsearch(prefixsum , n , k) 
    {
        // Initialize result
        var ans = -1;

        // Do Binary Search for largest
        // subarray size
        var left = 1, right = n;

        while (left <= right) {
            var mid = parseInt((left + right) / 2);

            // Check for all subarrays after mid
            var i;
            for (i = mid; i <= n; i++) {

                // Checking if all the subarrays
                // of a size is less than k.
                if (prefixsum[i] - prefixsum[i - mid] > k)
                    break;
            }

            // All subarrays of size mid have
            // sum less than or equal to k
            if (i == n + 1) {
                left = mid + 1;
                ans = mid;
            }

            // We found a subarray of size mid
            // with sum greater than k
            else
                right = mid - 1;
        }

        return ans;
    }

    // Return the maximum subarray size, such
    // that all subarray of that size have
    // sum less than K.
    function maxSize(arr , n , k) {

        // Initialize prefix sum array as 0.
        var prefixsum = Array(n + 1).fill(0);
    
        // Finding prefix sum of the array.
        for (i = 0; i < n; i++)
            prefixsum[i + 1] = prefixsum[i] + arr[i];

        return bsearch(prefixsum, n, k);
    }

    // Driver code
        var arr = [ 1, 2, 10, 4 ];
        var n = arr.length;
        var k = 14;
        document.write(maxSize(arr, n, k));

// This code contributed by Rajput-Ji

</script>
PHP
<?php 
// PHP program to find maximum subarray 
// size, such that all subarrays of that 
// size have sum less than K.

// Search for the maximum length of 
// required subarray.
function bsearch(&$prefixsum, $n, $k)
{
    // Initialize result
    $ans = -1; 

    // Do Binary Search for largest 
    // subarray size 
    $left = 1;
    $right = $n;
    while ($left <= $right)
    {
        $mid = intval(($left + $right) / 2);

        // Check for all subarrays after mid
        for ($i = $mid; $i <= $n; $i++)
        {
            // Checking if all the subarrays
            // of a size less than k.
            if ($prefixsum[$i] - $prefixsum[$i - 
                                 $mid] > $k)
                break;
        }

        // All subarrays of size mid have 
        // sum less than or equal to k
        if ($i == $n + 1)
        {
            $left = $mid + 1;
            $ans = $mid;
        }

        // We found a subarray of size mid 
        // with sum greater than k
        else
            $right = $mid - 1;
    }
    return $ans;
}

// Return the maximum subarray size,
// such that all subarray of that size
// have sum less than K.
function maxSize(&$arr, $n, $k)
{
    // Initialize prefix sum array as 0.
    $prefixsum = array_fill(0, $n + 1, NULL);

    // Finding prefix sum of the array.
    for ($i = 0; $i < $n; $i++)
        $prefixsum[$i + 1] = $prefixsum[$i] + 
                             $arr[$i];

    return bsearch($prefixsum, $n, $k);
}

// Driver code
$arr = array(1, 2, 10, 4);
$n = sizeof($arr);
$k = 14;
echo maxSize($arr, $n, $k) . "\n";

// This code is contributed 
// by ChitraNayal
?>

Output
2

Time Complexity: O(n log n), where N represents the size of the given array.
Auxiliary Space: O(n), where N represents the size of the given array.

Efficient Approach: This method uses the Sliding Window Technique to solve the given problem. 

  • The approach is to find the minimum subarray size whose sum is greater than integer k.
  • Increase the window size from the end up to which the sum of that window is greater than k.
  • Now, store that subarray size if it is smaller than the already stored subarray size (in variable ans).
  • Now, decrement the subarray size from the beginning. The variable ans will store the minimum subarray size whose sum is greater than k.
  • At last, (ans-1) is the actual answer. Then, that subarray size – 1 is the maximum subarray size, such that all subarray of that size will have sum less than or equal to k.

Implementation:

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to find the 
// largest size subarray
void func(vector<int> arr, 
          int k, int n)
{
    // Variable declaration
    int ans = n;
    int sum = 0;
    int start = 0;
    bool not_possible = false;
    // Loop till N
    for (int end = 0; end < n; end++)
    {
        // Sliding window from left
        sum += arr[end];

        while (sum > k) {
            // Sliding window from right
            sum -= arr[start];
            start++;

            // Storing sub-array size - 1
            // for which sum was greater than k
            ans = min(ans, end - start + 1);

            // Sum will be 0 if start>end
            // because all elements are positive
            // start>end only when arr[end]>k i.e,
            // there is an array element with
            // value greater than k, so sub-array
            // sum cannot be less than k.
            if (sum == 0){
                not_possible = true;
                break;
            }
        }
        if(not_possible){
            ans = -1;
            break;
        }
    }

    // Print the answer
    cout << ans;
}

// Driver code
int main()
{
    vector<int> arr{ 1, 2, 3, 4 };
    int k = 8;
    int n = arr.size();

    // Function call
    func(arr, k, n);

    return 0;
}

// This code is improved by Susobhan Akhuli
Java
// Java program for the above approach
import java.io.*;

class GFG {

    // Function to find the
    // largest size subarray
    public static void func(int arr[], int k, int n)
    {

        // Variable declaration
        int ans = n;
        int sum = 0;
        int start = 0;
        boolean not_possible = false;
        // Loop till N
        for (int end = 0; end < n; end++) {

            // Sliding window from left
            sum += (int)arr[end];

            while (sum > k) {

                // Sliding window from right
                sum -= (int)arr[start];
                start++;

                // Storing sub-array size - 1
                // for which sum was greater than k
                ans = Math.min(ans, end - start + 1);

                // Sum will be 0 if start>end
                // because all elements are positive
                // start>end only when arr[end]>k i.e,
                // there is an array element with
                // value greater than k, so sub-array
                // sum cannot be less than k.
                if (sum == 0) {
                    not_possible = true;
                    break;
                }
            }
            if (not_possible) {
                ans = -1;
                break;
            }
        }

        // Print the answer
        System.out.println(ans);
    }

    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4 };
        int k = 8;
        int n = arr.length;

        // Function call
        func(arr, k, n);
    }
}

// This code is contributed by rag2127
// This code is improved by Susobhan Akhuli
Python3
# Python3 program for the above approach

# Function to find the 
# largest size subarray
def func(arr, k, n):
    
    # Variable declaration
    ans = n
    Sum = 0
    start = 0
    not_possible = False
    
    # Loop till N
    for end in range(n):

        # Sliding window from left
        Sum += arr[end]

        while (Sum > k):
            
            # Sliding window from right
            Sum -= arr[start]
            start += 1

            # Storing sub-array size - 1
            # for which sum was greater than k
            ans = min(ans, end - start + 1)

            # Sum will be 0 if start>end
            # because all elements are positive
            # start>end only when arr[end]>k i.e,
            # there is an array element with
            # value greater than k, so sub-array
            # sum cannot be less than k.
            if (Sum == 0):
                not_possible = True
                break
                
        if (not_possible):
            ans = -1
            break
            
    # Print the answer
    print(ans)

# Driver code
arr = [ 0, 2, 3, 4 ]
k = 8
n = len(arr)

# Function call
func(arr, k, n)

# This code is contributed by avanitrachhadiya2155
# This code is improved by Susobhan Akhuli
C#
// C# program for the above approach
using System; 
using System.Collections;

class GFG{
     
// Function to find the 
// largest size subarray
static void func(ArrayList arr, 
                 int k, int n)
{
    
    // Variable declaration
    int ans = n;
    int sum = 0;
    int start = 0;
    bool not_possible = false;
    // Loop till N
    for(int end = 0; end < n; end++)
    {
        
        // Sliding window from left
        sum += (int)arr[end];
 
        while (sum > k) 
        {
            
            // Sliding window from right
            sum -= (int)arr[start];
            start++;
 
            // Storing sub-array size - 1
            // for which sum was greater than k
            ans = Math.Min(ans, end - start + 1);
 
            // Sum will be 0 if start>end
            // because all elements are positive
            // start>end only when arr[end]>k i.e,
            // there is an array element with
            // value greater than k, so sub-array
            // sum cannot be less than k.
            if (sum == 0){
                not_possible = true;
                break;
            }
        }
        if(not_possible){
            ans = -1;
            break;
        }
    }
    
    // Print the answer
    Console.Write(ans);
}
 
// Driver code
public static void Main(string[] args)
{
    ArrayList arr = new ArrayList(){ 1, 2, 3, 4 };
    int k = 8;
    int n = arr.Count;
 
    // Function call
    func(arr, k, n);
}
}

// This code is contributed by rutvik_56
// This code is improved by Susobhan Akhuli
JavaScript
<script>
// Javascript program for the above approach

// Function to find the 
// largest size subarray
function func(arr, k, n)
{
    // Variable declaration
    let ans = n;
    let sum = 0;
    let start = 0;
    let not_possible = false;
    
    // Loop till N
    for (let end = 0; end < n; end++)
    {
        // Sliding window from left
        sum += arr[end];

        while (sum > k) {
            // Sliding window from right
            sum -= arr[start];
            start++;

            // Storing sub-array size - 1
            // for which sum was greater than k
            ans = Math.min(ans, end - start + 1);

            // Sum will be 0 if start>end
            // because all elements are positive
            // start>end only when arr[end]>k i.e,
            // there is an array element with
            // value greater than k, so sub-array
            // sum cannot be less than k.
            if (sum == 0){
                not_possible = true;
                break;
            }
        }
        if(not_possible){
            ans = -1;
            break;
        }
    }

    // Print the answer
    document.write(ans);
}

// Driver code
    let arr = [ 1, 2, 3, 4 ];
    let k = 8;
    let n = arr.length;

    // Function call
    func(arr, k, n);
    
// This code is improved by Susobhan Akhuli
</script>

Output
2

Time Complexity: O(N), where N represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.



Similar Reads

Maximum size of square such that all submatrices of that size have sum less than K
Given an N x M matrix of integers and an integer K, the task is to find the size of the maximum square sub-matrix (S x S), such that all square sub-matrices of the given matrix of that size have a sum less than K. Examples: Input: K = 30 mat[N][M] = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4} }; Output: 2 Explanation: All Su
15+ min read
Maximum length L such that the sum of all subarrays of length L is less than K
Given an array of length N and an integer K. The task is to find the maximum length L such that all the subarrays of length L have sum of its elements less than K.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 20 Output: 5 The only subarray of length 5 is the complete array and (1 + 2 + 3 + 4 + 5) = 15 &lt; 20. Input: arr[] = {1, 2, 3, 4, 5}, K = 10
8 min read
Maximum sum subarray of size K with sum less than X
Given an array arr[] and two integers K and X, the task is to find the maximum sum among all subarrays of size K with the sum less than X. Examples: Input: arr[] = {20, 2, 3, 10, 5}, K = 3, X = 20Output: 18Explanation: Subarray of size 3 having maximum sum less than 20 is {3, 10, 5}. Therefore, required output is 18. Input: arr[] = {-5, 8, 7, 2, 10
7 min read
Maximum sum subarray having sum less than given sum using Set
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum
7 min read
Maximum sum subarray having sum less than or equal to given sum
Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array. Note: Given array contains only non-negative integers. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } sum = 11Output: 10Subarray having maximum sum is { 1, 2, 3, 4 }Input: arr[] = { 2, 4, 6, 8, 10
10 min read
Count Subarrays with product of sum and subarray length less than K
Given an array of positive elements arr[] of length N, the task is to count all the subarrays such that the product of the subarray sum and length of the subarray should be strictly less than K. Examples: Input: arr[] = {6, 2, 1, 4, 3}, K = 10Output: 6Explanation: There are six valid subarrays: {6}, {2}, {1}, {4}, {3}, {2, 1} Input: arr[] = {1, 4,
13 min read
Split array into K subarrays such that sum of maximum of all subarrays is maximized
Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print "-1". Examples: Input: arr[] = {5, 3, 2, 7, 6, 4},
11 min read
Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k
Given an array arr[] and an integer k, the task is to find the maximum product from the array such that the frequency sum of all repeating elements in the product is ≤ 2 * k, where frequency sum is the sum of frequencies of all the elements in the product that appear more than once. For example, if we choose a product 1 * 1 * 2 * 3 * 4 * 5 * 6 * 6
7 min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 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
First subarray having sum at least half the maximum sum of any subarray of size K
Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum possible sum from any subarray of size K is 16 fr
9 min read
Split array to three subarrays such that sum of first and third subarray is equal and maximum
Given an array of N integers, the task is to print the sum of the first subarray by splitting the array into exactly three subarrays such that the sum of the first and third subarray elements are equal and the maximum. Note: All the elements must belong to a subarray and the subarrays can also be empty. Examples: Input: a[] = {1, 3, 1, 1, 4} Output
13 min read
Minimum flips in a Binary array such that XOR of consecutive subarrays of size K have different parity
Given a binary array arr[] of length N, the task is to find the minimum flips required in the array such that XOR of a consecutive sub-arrays of size K have different parity.Examples: Input: arr[] = {0, 1, 0, 1, 1}, K = 2 Output: 2 Explanation: For the above given array XOR of consecutive sub-array of size 2 is: {(0, 1): 1, (1, 0): 1, (0, 1): 1, (1
9 min read
Sum of all array elements less than X and greater than Y for Q queries
Given a sorted array arr[], and a set Q having M queries, where each query has values X and Y, the task is to find the sum of all integers less than X and greater than Y present in the array. Note: X and Y may or may not be present in the array. Examples: Input: arr[] = [3 5 8 12 15], Q = {{5, 12}, {4, 8}} Output: 18 30 Explanation: For query 1, X
9 min read
For each A[i] find smallest subset with all elements less than A[i] sum more than B[i]
Given two arrays A[] and B[] of N integers, the task is to find for each element A[i], the size of the smallest subset S of indices, such that : Each value corresponding to the indices in subset S is strictly less than A[i].Sum of elements corresponding to the indices in B is strictly greater than B[i]. Examples: Input: N = 5, A = {3, 2, 100, 4, 5}
10 min read
Smallest subarray of size greater than K with sum greater than a given value
Given an array, arr[] of size N, two positive integers K and S, the task is to find the length of the smallest subarray of size greater than K, whose sum is greater than S. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 1, S = 8Output: 2Explanation: Smallest subarray with sum greater than S(=8) is {4, 5}Therefore, the required output is 2. Input: ar
15 min read
Largest number less than N with digit sum greater than the digit sum of N
Given an integer N, the task is to find the greatest number less than N such that the sum of its digits is greater than the sum of the digits of N. If the condition isn't satisfied for any number then print -1.Examples: Input: N = 100 Output: 99 99 is the largest number less than 100 sum of whose digits is greater than the sum of the digits of 100I
9 min read
Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
Given two unsorted arrays arr1[] and arr2[], the task is to find the sum of elements of arr1[] such that the number of elements less than or equal to them in arr2[] is maximum. Examples: Input: arr1[] = {1, 2, 3, 4, 7, 9}, arr2[] = {0, 1, 2, 1, 1, 4} Output: 20 Below table shows the count of elements in arr2[] which are ? the elements of arr1[] arr
15 min read
Split into K subarrays to minimize the maximum sum of all subarrays
Given an Array[] of N elements and a number K. ( 1 &lt;= K &lt;= N ) . Split the given array into K subarrays (they must cover all the elements). The maximum subarray sum achievable out of K subarrays formed, must be the minimum possible. Find that possible subarray sum.Examples: Input : Array[] = {1, 2, 3, 4}, K = 3 Output : 4 Optimal Split is {1,
15 min read
Find all possible subarrays having product less than or equal to K
Given an array arr[], the task is to print all possible subarrays having a product of its elements less than or equal to K. Input: arr[] = {2, 1, 3, 4, 5, 6, 2}, K = 10 Output: [[2], [1], [2, 1], [3], [1, 3], [2, 1, 3], [4], [5], [6], [2]] Explanation: All possible subarrays having product ? K are {2}, {1}, {2, 1}, {3}, {1, 3}, {2, 1, 3}, {4}, {5},
13 min read
Maximum length of subarray such that all elements are equal in the subarray
Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements. Input: arr[] = {1, 2, 3, 4} Output: 1 Explanation: All identical elemen
5 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
Find an N-length permutation that contains subarrays with sum less than Bitwise XOR
Given a positive integer N, the task is to find a permutation of length N having Bitwise OR of any of its subarray greater than or equal to the length of the subarray. Examples: Input: N = 5 Output: 1 3 5 2 4 Explanation: Consider the subarray {1, 3, 5} from the permutation {1, 3, 5, 2, $}. Length of the subarray = 3 Bitwise OR of the subarray = 1
3 min read
Maximum size square Sub-Matrix with sum less than or equals to K
Given a Matrix arr[][] of size M x N having positive integers and a number K, the task is to find the size of the largest square sub-matrix whose sum of elements is less than or equals to K. Example: Input: arr[][] = { { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 } }, K = 4 Output: 2 Explanation: Maximum size square Sub-M
12 min read
Sum of elements of all partitions of number such that no element is less than K
Given an integer N, the task is to find an aggregate sum of all integer partitions of this number such that each partition does not contain any integer less than K. Examples: Input: N = 6 and K = 2 Output: 24 In this case, there are 4 valid partitions. 1) {6} 2) {4, 2} 3) {3, 3} 4) {2, 2, 2} Therefore, aggregate sum would be 6 + 4 + 2 + 3 + 3 + 2 +
9 min read
Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements
Given an array of N integers, the task is to arrange them in a circular arrangement in such a way that the element is strictly less than the sum of its adjacent elements. In case such an arrangement is not possible, then print -1. Note that there can be multiple ways of arranging the elements such that the condition is satisfied and the task is to
8 min read
Minimum area such that all submatrix of the size have same maximum value
Given an N*M matrix Mat[][] containing all distinct integers, the task is to find the minimum area of the matrix (r*c, where 1 ≤ r ≤ N and 1 ≤ c ≤ M ) for every submatrix of size r*c the maximum value remains the same. Examples: Input: N = 4, M = 4, Mat[][] = {{9, 12, 6, 11}, {3, 15, 19, 4}, {1, 13, 8, 11}, {14, 7, 9, 15}}Output: 3, 3Explanation: T
7 min read
Largest number with maximum trailing nines which is less than N and greater than N-D
Given two numbers N and D. The task is to find out the largest number smaller than or equal to N which contains the maximum number of trailing nines and the difference between N and the number should not be greater than D. Examples: Input: N = 1029, D = 102 Output: 999 1029 has 1 trailing nine while 999 has three trailing nine. Also 1029-999 = 30(w
14 min read
Split array into maximum subarrays such that every distinct element lies in a single subarray
Given an array, arr[] of size N, the task is to split the array into the maximum number of subarrays such that the first and the last occurrence of all distinct array element lies in a single subarray. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Split the array into subarrays {1, 1} and {2, 2}.Therefore, the required output is 2. Inpu
6 min read
Count of subarrays starting or ending at an index i such that arr[i] is maximum in subarray
Given an array arr[] consisting of N integers, the task is to find the number of subarrays starting or ending at an index i such that arr[i] is the maximum element of the subarray. Examples: Input: arr[] = {3, 4, 1, 6, 2}Output: 1 3 1 5 1Explanation: The subarray starting or ending at index 0 and with maximum arr[0](=3) is {3}. Therefore, the count
11 min read
three90RightbarBannerImg