The Wayback Machine - https://web.archive.org/web/20240815003338/https://www.geeksforgeeks.org/sliding-window-maximum-set-2/
Open In App

Sliding Window Maximum : Set 2

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

Set 1: Sliding Window Maximum (Maximum of all subarrays of size k).
Given an array arr of size N and an integer K, the task is to find the maximum for each and every contiguous subarray of size K.

Examples: 

Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 
Output: 3 3 4 5 5 5 6 
All contiguous subarrays of size k are 
{1, 2, 3} => 3 
{2, 3, 1} => 3 
{3, 1, 4} => 4 
{1, 4, 5} => 5 
{4, 5, 2} => 5 
{5, 2, 3} => 5 
{2, 3, 6} => 6

Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4 
Output: 10 10 10 15 15 90 90  

Approach: To solve this in lesser space complexity we can use two pointer technique.  

  • The first variable pointer iterates through the subarray and finds the maximum element of a given size K
  • The second variable pointer marks the ending index of the first variable pointer i.e., (i + K – 1)th index.
  • When the first variable pointer reaches the index of the second variable pointer, the maximum of that subarray has been computed and will be printed.
  • The process is repeated until the second variable pointer reaches the last array index (i.e array_size – 1).

Below is the implementation of the above approach: 

C++




// C++ program to find the maximum for each
// and every contiguous subarray of size K
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum for each
// and every contiguous subarray of size k
void printKMax(int a[], int n, int k)
{
    // If k = 1, print all elements
    if (k == 1) {
        for (int i = 0; i < n; i += 1)
            cout << a[i] << " ";
        return;
    }
 
    // Using p and q as variable pointers
    // where p iterates through the subarray
    // and q marks end of the subarray.
    int p = 0,
        q = k - 1,
        t = p,
        max = a[k - 1];
 
    // Iterating through subarray.
    while (q <= n - 1) {
 
        // Finding max
        // from the subarray.
        if (a[p] > max)
            max = a[p];
 
        p += 1;
 
        // Printing max of subarray
        // and shifting pointers
        // to next index.
        if (q == p && p != n) {
            cout << max << " ";
            q++;
            p = ++t;
 
            if (q < n)
                max = a[q];
        }
    }
}
 
// Driver Code
int main()
{
    int a[] = { 1, 2, 3, 4, 5,
                6, 7, 8, 9, 10 };
    int n = sizeof(a) / sizeof(a[0]);
    int K = 3;
 
    printKMax(a, n, K);
 
    return 0;
}


Java




// Java program to find the maximum for each
// and every contiguous subarray of size K
import java.util.*;
 
class GFG{
  
// Function to find the maximum for each
// and every contiguous subarray of size k
static void printKMax(int a[], int n, int k)
{
    // If k = 1, print all elements
    if (k == 1) {
        for (int i = 0; i < n; i += 1)
            System.out.print(a[i]+ " ");
        return;
    }
  
    // Using p and q as variable pointers
    // where p iterates through the subarray
    // and q marks end of the subarray.
    int p = 0,
        q = k - 1,
        t = p,
        max = a[k - 1];
  
    // Iterating through subarray.
    while (q <= n - 1) {
  
        // Finding max
        // from the subarray.
        if (a[p] > max)
            max = a[p];
  
        p += 1;
  
        // Printing max of subarray
        // and shifting pointers
        // to next index.
        if (q == p && p != n) {
            System.out.print(max+ " ");
            q++;
            p = ++t;
  
            if (q < n)
                max = a[q];
        }
    }
}
  
// Driver Code
public static void main(String[] args)
{
    int a[] = { 1, 2, 3, 4, 5,
                6, 7, 8, 9, 10 };
    int n = a.length;
    int K = 3;
  
    printKMax(a, n, K);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to find the maximum for each
# and every contiguous subarray of size K
 
# Function to find the maximum for each
# and every contiguous subarray of size k
def printKMax(a, n, k):
     
    # If k = 1, print all elements
    if (k == 1):
        for i in range(n):
            print(a[i], end=" ");
        return;
         
    # Using p and q as variable pointers
    # where p iterates through the subarray
    # and q marks end of the subarray.
    p = 0;
    q = k - 1;
    t = p;
    max = a[k - 1];
 
    # Iterating through subarray.
    while (q <= n - 1):
 
        # Finding max
        # from the subarray.
        if (a[p] > max):
            max = a[p];
        p += 1;
 
        # Printing max of subarray
        # and shifting pointers
        # to next index.
        if (q == p and p != n):
            print(max, end=" ");
            q += 1;
            p = t + 1;
            t = p;
 
            if (q < n):
                max = a[q];
 
# Driver Code
if __name__ == '__main__':
    a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    n = len(a);
    K = 3;
 
    printKMax(a, n, K);
 
# This code is contributed by Princi Singh


C#




// C# program to find the maximum for each
// and every contiguous subarray of size K
using System;
 
class GFG{
   
// Function to find the maximum for each
// and every contiguous subarray of size k
static void printKMax(int []a, int n, int k)
{
    // If k = 1, print all elements
    if (k == 1) {
        for (int i = 0; i < n; i += 1)
            Console.Write(a[i]+ " ");
        return;
    }
   
    // Using p and q as variable pointers
    // where p iterates through the subarray
    // and q marks end of the subarray.
    int p = 0,
        q = k - 1,
        t = p,
        max = a[k - 1];
   
    // Iterating through subarray.
    while (q <= n - 1) {
   
        // Finding max
        // from the subarray.
        if (a[p] > max)
            max = a[p];
   
        p += 1;
   
        // Printing max of subarray
        // and shifting pointers
        // to next index.
        if (q == p && p != n) {
            Console.Write(max+ " ");
            q++;
            p = ++t;
   
            if (q < n)
                max = a[q];
        }
    }
}
   
// Driver Code
public static void Main(String[] args)
{
    int []a = { 1, 2, 3, 4, 5,
                6, 7, 8, 9, 10 };
    int n = a.Length;
    int K = 3;
   
    printKMax(a, n, K);
}
}
  
// This code is contributed by Rajput-Ji


Javascript




<script>
// Javascript program to find the maximum for each
// and every contiguous subarray of size K
 
// Function to find the maximum for each
// and every contiguous subarray of size k
function printKMax(a, n, k)
{
    // If k = 1, print all elements
    if (k == 1) {
        for (let i = 0; i < n; i += 1)
            document.write(a[i] + " ");
        return;
    }
 
    // Using p and q as variable pointers
    // where p iterates through the subarray
    // and q marks end of the subarray.
    let p = 0, q = k - 1, t = p, max = a[k - 1];
 
    // Iterating through subarray.
    while (q <= n - 1) {
 
        // Finding max
        // from the subarray.
        if (a[p] > max)
            max = a[p];
 
        p += 1;
 
        // Printing max of subarray
        // and shifting pointers
        // to next index.
        if (q == p && p != n) {
            document.write(max + " ");
            q++;
            p = ++t;
 
            if (q < n)
                max = a[q];
        }
    }
}
 
// Driver Code
 
let a = [ 1, 2, 3, 4, 5,
            6, 7, 8, 9, 10 ];
let n = a.length
let K = 3;
 
printKMax(a, n, K);
</script>


Output

3 4 5 6 7 8 9 10 

Time Complexity: O(N*k) 
Auxiliary Space Complexity: O(1)
 

Approach 2: Using Dynamic Programming:

  • Firstly, divide the entire array into blocks of k elements such that each block contains k elements of the array(not always for the last block).
  • Maintain two dp arrays namely, left and right.
  • left[i] is the maximum of all elements that are to the left of current element(including current element) in the current block(block in which current element is present).
  • Similarly, right[i] is the maximum of all elements that are to the right of current element(including current element) in the current block(block in which current element is present).
  • Finally, when calculating the maximum element in any subarray of length k, we calculate the maximum of right[l] and left[r]
    where l = starting index of current sub array, r = ending index of current sub array

Below is the implementation of above approach,

C++




// C++ program to find the maximum for each
// and every contiguous subarray of size K
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum for each
// and every contiguous subarray of size k
void printKMax(int a[], int n, int k)
{
    // If k = 1, print all elements
    if (k == 1) {
        for (int i = 0; i < n; i += 1)
            cout << a[i] << " ";
        return;
    }
     
      //left[i] stores the maximum value to left of i in the current block
      //right[i] stores the maximum value to the right of i in the current block
    int left[n],right[n];
   
      for(int i=0;i<n;i++){
          //if the element is starting element of that block
        if(i%k == 0) left[i] = a[i];
          else left[i] = max(left[i-1],a[i]);
           
          //if the element is ending element of that block
          if((n-i)%k == 0 || i==0) right[n-1-i] = a[n-1-i];
          else right[n-1-i] = max(right[n-i],a[n-1-i]);
    }
   
      for(int i=0,j=k-1; j<n; i++,j++)
         cout << max(left[j],right[i]) << ' ';
}
 
// Driver Code
int main()
{
    int a[] = { 1, 2, 3, 4, 5,
                6, 7, 8, 9, 10 };
    int n = sizeof(a) / sizeof(a[0]);
    int K = 3;
 
    printKMax(a, n, K);
 
    return 0;
}


Java




// Java program to find the maximum for each
// and every contiguous subarray of size K
import java.util.*;
 
class GFG
{
 
  // Function to find the maximum for each
  // and every contiguous subarray of size k
  static void printKMax(int a[], int n, int k)
  {
 
    // If k = 1, print all elements
    if (k == 1) {
      for (int i = 0; i < n; i += 1)
        System.out.print(a[i] + " ");
      return;
    }
 
    // left[i] stores the maximum value to left of i in the current block
    // right[i] stores the maximum value to the right of i in the current block
    int left[] = new int[n];
    int right[] = new int[n];
 
    for (int i = 0; i < n; i++)
    {
 
      // if the element is starting element of that block
      if (i % k == 0)
        left[i] = a[i];
      else
        left[i] = Math.max(left[i - 1], a[i]);
 
      // if the element is ending element of that block
      if ((n - i) % k == 0 || i == 0)
        right[n - 1 - i] = a[n - 1 - i];
      else
        right[n - 1 - i] = Math.max(right[n - i], a[n - 1 - i]);
    }
 
    for (int i = 0, j = k - 1; j < n; i++, j++)
      System.out.print(Math.max(left[j], right[i]) + " ");
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int n = a.length;
    int K = 3;
 
    printKMax(a, n, K);
 
  }
}
 
// This code is contributed by gauravrajput1


Python3




# Python3 program to find the maximum for each
# and every contiguous subarray of size K
# Function to find the maximum for each
# and every contiguous subarray of size k
def printKMax(a, n, k):
 
    # If k = 1, print all elements
    if (k == 1):
        for i in range(n):
            print(a[i],end = " ")
        return
 
    # left[i] stores the maximum value to left of i in the current block
    # right[i] stores the maximum value to the right of i in the current block
    left = [ 0 for i in range(n)]
    right = [ 0 for i in range(n)]
 
    for i in range(n):
 
        # if the element is starting element of that block
        if (i % k == 0):
            left[i] = a[i]
        else:
            left[i] = max(left[i - 1], a[i])
 
        # if the element is ending element of that block
        if ((n - i) % k == 0 or i == 0):
            right[n - 1 - i] = a[n - 1 - i]
        else:
            right[n - 1 - i] = max(right[n - i], a[n - 1 - i])
 
    i = 0
    j = k - 1
 
    while j < n:
        print(max(left[j], right[i]),end = " ")
        i += 1
        j += 1
 
# Driver Code
a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
n = len(a)
K = 3
 
printKMax(a, n, K)
 
# This code is contributed by shinjanpatra


C#




// C# program to find the maximum for each
// and every contiguous subarray of size K
using System;
 
class GFG
{
 
  // Function to find the maximum for each
  // and every contiguous subarray of size k
  static void printKMax(int []a, int n, int k)
  {
 
    // If k = 1, print all elements
    if (k == 1) {
      for (int i = 0; i < n; i += 1)
        Console.Write(a[i] + " ");
      return;
    }
 
    // left[i] stores the maximum value to left of i in the current block
    // right[i] stores the maximum value to the right of i in the current block
    int []left = new int[n];
    int []right = new int[n];
 
    for (int i = 0; i < n; i++)
    {
 
      // if the element is starting element of that block
      if (i % k == 0)
        left[i] = a[i];
      else
        left[i] = Math.Max(left[i - 1], a[i]);
 
      // if the element is ending element of that block
      if ((n - i) % k == 0 || i == 0)
        right[n - 1 - i] = a[n - 1 - i];
      else
        right[n - 1 - i] = Math.Max(right[n - i], a[n - 1 - i]);
    }
 
    for (int i = 0, j = k - 1; j < n; i++, j++)
      Console.Write(Math.Max(left[j], right[i]) + " ");
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int n = a.Length;
    int K = 3;
 
    printKMax(a, n, K);
 
  }
}
 
// This code is contributed by shivanisinghss2110


Javascript




<script>
 
// JavaScript program to find the maximum for each
// and every contiguous subarray of size K
// Function to find the maximum for each
// and every contiguous subarray of size k
function printKMax(a, n, k)
  {
 
    // If k = 1, print all elements
    if (k == 1) {
      for (var i = 0; i < n; i += 1)
        document.write(a[i] + " ");
      return;
    }
 
    // left[i] stores the maximum value to left of i in the current block
    // right[i] stores the maximum value to the right of i in the current block
    var left = [n];
    var right = [n];
 
    for (var i = 0; i < n; i++)
    {
 
      // if the element is starting element of that block
      if (i % k == 0)
        left[i] = a[i];
      else
        left[i] = Math.max(left[i - 1], a[i]);
 
      // if the element is ending element of that block
      if ((n - i) % k == 0 || i == 0)
        right[n - 1 - i] = a[n - 1 - i];
      else
        right[n - 1 - i] = Math.max(right[n - i], a[n - 1 - i]);
    }
 
    for (var i = 0, j = k - 1; j < n; i++, j++)
      document.write(Math.max(left[j], right[i]) + " ");
  }
 
  // Driver Code
    var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
    var n = a.length;
    var K = 3;
 
    printKMax(a, n, K);
 
// This code is contributed by shivanisinghss2110
 
</script>


Output

3 4 5 6 7 8 9 10 

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



Similar Reads

Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time
Given an array arr[] of N integers and another integer k ? N. The task is to find the maximum element of every sub-array of size k. Examples: Input: arr[] = {9, 7, 2, 4, 6, 8, 2, 1, 5} k = 3 Output: 9 7 6 8 8 8 5 Explanation: Window 1: {9, 7, 2}, max = 9 Window 2: {7, 2, 4}, max = 7 Window 3: {2, 4, 6}, max = 6 Window 4: {4, 6, 8}, max = 8 Window 5
8 min read
Sliding Window Maximum (Maximum of all subarrays of size K)
Given an array and an integer K, find the maximum for each and every contiguous subarray of size K. Examples :  Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 Output: 3 3 4 5 5 5 6Explanation: Maximum of 1, 2, 3 is 3                       Maximum of 2, 3, 1 is 3                       Maximum of 3, 1, 4 is 4                       Maximum of 1, 4,
15+ min read
Median of sliding window in an array | Set 2
Prerequisites: Policy based data structure, Sliding window technique.Given an array of integer arr[] and an integer K, the task is to find the median of each window of size K starting from the left and moving towards the right by one position each time.Examples: Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, K = 3 Output: 5 8 8 3 3 3 Explanation: 1st W
14 min read
Sliding Window Problems | Identify, Solve and Interview Questions
When we are dealing with problems that require checking answers of some ranges in an array, the Sliding window algorithm can be a very powerful technique. What are Sliding Window Problems?Sliding window problems are computational problems in which a fixed/variable-size window is moved through a data structure, typically an array or string, to effic
4 min read
CSES Solutions - Sliding Window Cost
You are given an array arr[] of N integers. Your task is to calculate for each window of K elements, from left to right, the minimum total cost of making all elements equal. You can increase or decrease each element with cost X, where X is the difference between the new and the original value. The total cost is the sum of such costs. Examples: Inpu
12 min read
Sliding Window Technique
Sliding Window problems are problems in which a fixed or variable-size window is moved through a data structure, typically an array or string, to solve problems efficiently based on continuous subsets of elements. This technique is used when we need to find subarrays or substrings according to a given set of conditions. Table of Content What is Sli
15+ min read
Maximum possible sum of a window in an array such that elements of same window in other array are unique
Given two arrays A and B of equal number of elements. The task is to find the maximum sum possible of a window in array B such that elements of same window in A[] are unique. Examples: Input: A = [0, 1, 2, 3, 0, 1, 4] B = [9, 8, 1, 2, 3, 4, 5] Output: sum = 20 The maximum sum possible in B[] such that all corresponding elements in A[] are unique is
10 min read
Minimum window size containing atleast P primes in every window of given range
Given three integers X, Y and P, the task is to find the minimum window size K such that every window in the range [X, Y] of this size have atleast P prime numbers.Examples: Input: X = 2, Y = 8, P = 2 Output: 4 Explanation: In the range [2, 8], window size of 4 contains atleast 2 primes in each window. Possible Windows - {2, 3, 4, 5} - No of Primes
15+ min read
Find maximum of minimum for every window size in a given array
Given an integer array arr[] of size N, find the maximum of the minimums for every window size in the given array. Note: The window size varies from 1 to N. Example: Input: arr[] = {10, 20, 30, 50, 10, 70, 30} Output: 70, 30, 20, 10, 10, 10, 10Explanation:The first element in the output indicates the maximum of minimums of all windows of size 1. Mi
15+ min read
Maximum XOR value of maximum and second maximum element among all possible subarrays
Given an array arr[] of N distinct positive integers, let's denote max(i, j) and secondMax(i, j) as the maximum and the second maximum element of the subarray arr[i...j]. The task is to find the maximum value of max(i, j) XOR secondMax(i, j) for all possible values of i and j. Note that the size of the subarray must be at least two.Examples: Input:
5 min read
Panalphabetic window in a string
Given a string S of size n. The task is to check whether the given string contain panalphabetic window. A Panalphabetic window is a stretch of text that contains all the letters of the alphabet in order. Examples: Input : S = "abujm zvcd acefc deghf gijkle m n o p pafqrstuvwxyzfap" Output : YES Panalphabetic Window is in Bold: abujm zvcd acefc degh
5 min read
Window to Viewport Transformation in Computer Graphics with Implementation
Window to Viewport Transformation is the process of transforming 2D world-coordinate objects to device coordinates. Objects inside the world or clipping window are mapped to the viewport which is the area on the screen where world coordinates are mapped to be displayed. General Terms: World coordinate - It is the Cartesian coordinate w.r.t which we
8 min read
Program to find the final size of Congestion Window in TCP Reno
Given the initial congestion window size cwnd, threshold value ssthresh, connection time rtt and an array arr where arr[i] implies the time when a packet loss is detected. The task is to find the final congestion window size when all the packet drops are being encountered by the sender. The TCP Reno follows below conditions: The initial value of cw
7 min read
Find the final size of Congestion Window in TCP Tahoe
Given the initial congestion window size cwnd, threshold value ssthresh, connection time rtt and an array arr where arr[i] implies the time when a packet loss is detected. The task is to find the final congestion window size when all the packet drops are being encountered by the sender. The TCP Tahoe follows below conditions: The initial value of c
8 min read
Smallest window containing 0, 1 and 2
Given a string S of size N consisting of the characters 0, 1 and 2, the task is to find the length of the smallest substring of string S that contains all the three characters 0, 1 and 2. If no such substring exists, then return -1. Examples: Input: S = "01212"Output: 3Explanation: The substring 012 is the smallest substringthat contains the charac
13 min read
First negative integer in every window of size k
Given an array and a positive integer k, find the first negative integer for each window(contiguous subarray) of size k. If a window does not contain a negative integer, then print 0 for that window. Examples: Input : arr[] = {-8, 2, 3, -6, 10}, k = 2 Output : -8 0 -6 -6 First negative integer for each window of size k {-8, 2} = -8 {2, 3} = 0 (does
15+ min read
Smallest window that contains all characters of string itself
Given a string, find the smallest window length with all distinct characters of the given string. For eg. str = “aabcbcdbca”, then the result would be 4 as of the smallest window will be “dbca” .Examples:  Input: aabcbcdbcaOutput: dbcaExplanation: Possible substrings= {aabcbcd, abcbcd, bcdbca, dbca....}Of the set of possible substrings 'dbca' is th
15+ min read
Count distinct elements in every window of size k
Given an array of size N and an integer K, return the count of distinct numbers in all windows of size K. Examples: Input: arr[] = {1, 2, 1, 3, 4, 2, 3}, K = 4Output: 3 4 4 3Explanation: First window is {1, 2, 1, 3}, count of distinct numbers is 3 Second window is {2, 1, 3, 4} count of distinct numbers is 4 Third window is {1, 3, 4, 2} count of dis
12 min read
Smallest window in a String containing all characters of other String
Given two strings S (length m) and P (length n), the task is to find the smallest substring in S that contains all characters of P, including duplicates. If no such substring exists, return "-1". If multiple substrings of the same length are found, return the one with the smallest starting index. Examples: Input: S = "timetopractice", P = "toc"Outp
15+ min read
Maximum subset sum having difference between its maximum and minimum in range [L, R]
Given an array arr[] of N positive integers and a range [L, R], the task is to find the maximum subset-sum such that the difference between the maximum and minimum elements of the subset lies in the given range. Examples: Input: arr[] = {6, 5, 0, 9, 1}, L = 0, R = 3Output: 15Explanation: The subset {6, 9} of the given array has the difference betwe
9 min read
Maximum range length such that A[i] is maximum in given range for all i from [1, N]
Given an array arr[] consisting of N distinct integers. For each i (0 ? i &lt; n), find a range [l, r] such that A[i] = max(A[l], A[l+1], ..., A[r]) and l ? i ? r and r-l is maximized. Examples: Input: arr[] = {1, 3, 2}Output: {0 0}, {0 2}, {2 2}Explanation: For i=0, 1 is maximum in range [0, 0] only. For i=1, 3 is maximum in range [0, 2] and for i
8 min read
Maximum element in an array such that its previous and next element product is maximum
Given an array arr[] of N integers, the task is to print the largest element among the array such that its previous and next element product is maximum.Examples: Input: arr[] = {5, 6, 4, 3, 2} Output: 6 The product of the next and the previous elements for every element of the given array are: 5 -&gt; 2 * 6 = 12 6 -&gt; 5 * 4 = 20 4 -&gt; 6 * 3 = 1
6 min read
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
Let [Tex](a, b) [/Tex]represent the ordered pair of the second maximum and the maximum element of an array respectively. We need to find all such unique pairs overall contiguous sub-arrays of a given array. Examples: Input: Arr = [ 1, 2, 3, 4, 5 ] Output: (1, 2) (2, 3) (3, 4) (4, 5) Input: Arr = [ 1, 1, 2 ] Output: (1, 1) (1, 2) Input: Arr = [ 1, 2
13 min read
Maximum length Subsequence with alternating sign and maximum Sum
Given an array arr[] of size n having both positive and negative integer excluding zero. The task is to find the subsequence with an alternating sign having maximum size and maximum sum that is, in a subsequence sign of each adjacent element is opposite for example if the first one is positive then the second one has to be negative followed by anot
7 min read
Maximum increase in value of Matrix to keep maximum rows and columns unchanged
Given a matrix mat[][] of dimensionM*N, the task is to find the total maximum possible value must be increased to each cell(say mat[i][j]) such that maximum element of row i and column j remains unchanged. Examples: Input: N = 3, M = 3, mat[][] = { {4, 1, 3}, {3, 1, 1}, {2, 2, 0} } Output: 6 Explanation: The given matrix is: 4 1 3 3 1 1 2 2 0 Row-w
9 min read
Sum of maximum of all subarrays by adding even frequent maximum twice
Given an array arr[] consisting of N integers (All array elements are a perfect power of 2), the task is to calculate the sum of the maximum elements in all the subarrays. Note: If the frequency of the maximum element in a subarray is even, add twice the value of that element to the sum. Examples: Input: arr[] = {1, 2}Output: 5Explanation: All poss
15+ min read
Maximum sum of K-length subarray with maximum count of distinct prime factors
Given an array arr[] consisting of N positive integers and an integer K, the task is to find the maximum sum of array elements in a subarray having maximum sum of distinct prime factors in each K-length subarray. Note: If there are multiple answers then print the sum of the original subarray having maximum sum. Examples: Input: arr[] = {1, 4, 2, 10
11 min read
Distribute given arrays into K sets such that total sum of maximum and minimum elements of all sets is maximum
Given two arrays, the first arr[] of size N and the second brr[] of size K. The task is to divide the first array arr[] into K sets such that the i-th set should contain brr[i] elements from the second array brr[], and the total sum of maximum and minimum elements of all sets is maximum. Examples: Input: n = 4, k = 2, arr[] = {10, 10, 11, 11 }, brr
8 min read
Split array into maximum possible subsets having product of their length with the maximum element at least K
Given an array arr[] consisting of N integers and a positive integer K, the task is to maximize the number of subsets having a product of its size and its maximum element at least K by dividing array element into disjoint subsets. Examples: Input: N = 5, K = 4, arr[] = {1, 5, 4, 2, 3}Output: 3Explanation:The array can be split into 3 possible subse
6 min read
Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction)
A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matching for a given Bipartite Graph. We have di
3 min read
three90RightbarBannerImg