Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find the subarray with least average
Next article icon

Find the subarray with least average

Last Updated : 16 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[] of size n and integer k such that k <= n.

Examples : 

Input:  arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3 Output: Subarray between indexes 3 and 5 The subarray {20, 10, 50} has the least average  among all subarrays of size 3.  Input:  arr[] = {3, 7, 5, 20, -10, 0, 12}, k = 2 Output: Subarray between [4, 5] has minimum average

We strongly recommend that you click here and practice it, before moving on to the solution.

A Simple Solution is to consider every element as beginning of subarray of size k and compute sum of subarray starting with this element. Time complexity of this solution is O(nk).

Java
// java program code of Naive approach to // find subarray with minimum average import java.util.*;  class GFG {      static void findsubarrayleast(int arr[], int k, int n)     {         int min = Integer.MAX_VALUE;         int minindex = 0;         for (int i = 0; i <= n - k; i++) {             int sum = 0;             for (int j = i; j < i + k; j++) {                 sum += arr[j];             }             if (sum < min) {                 min = sum;                 minindex = i;             }         }         // printing the desired subarray         System.out.println(             "subarray with minimum average is: ");         for (int i = minindex; i < minindex + k; i++) {             System.out.print(arr[i] + " ");         }     }      // Driver Code     public static void main(String[] args)     {         // Test Case 1         int arr[] = {20, 3, 13, 5, 10, 14, 8, 5, 11, 9, 1, 11};         int n = arr.length;         int k = 9;          // function call         findsubarrayleast(arr, k, n);     } }  // This code is contributed by Aarti_Rathi 
C++
//C++ code of Naive approach to  //find subarray with minimum average  #include<bits/stdc++.h> using namespace std; //function to find subarray void findsubarrayleast(int arr[],int k,int n){     int min=INT_MAX,minindex;     for (int i = 0; i <= n-k; i++)     {         int sum=0;         for (int j = i; j < i+k; j++)         {             sum+=arr[j];         }         if(sum<min){             min=sum;             minindex=i;         }              }   //printing the desired subarray     cout<<"subarray with minimum average is: ";     for (int i = minindex; i < minindex+k; i++)     {         cout<<arr[i]<<" ";     }          } //driver code int main() { int arr[]={3, 7, 90, 20, 10, 50, 40}; int n=sizeof(arr)/sizeof(arr[0]),k=3; //function call findsubarrayleast(arr,k,n); return 0; }  //this code is contributed by Machhaliya Muhammad 
Python3
# Python3 program to find # minimum average subarray  # Prints beginning and ending # indexes of subarray of size k # with minimum average def findsubarrayleast(arr, k, n):     min = 999999     minindex = 0     for i in range(n-k+1):         sum = 0         j = i         for j in range(i, i+k):             sum += arr[j]         if sum < min:             min = sum             minindex = i      # printing the desired subarray     print("subarray with minimum average is: ", end='')     for i in range(minindex, minindex+k):         print(arr[i], end=" ")   # Driver Code arr = [20, 3, 13, 5, 10, 14, 8, 5, 11, 9, 1, 11] k = 9  # Subarray size n = len(arr) findsubarrayleast(arr, k, n)  # This code is contributed by Aarti_Rathi 
C#
// C# program code of Naive approach to //find subarray with minimum average using System;  class GFG {    static void findsubarrayleast(int []arr,int k,int n){     int min = Int32.MaxValue;     int minindex = 0;     for (int i = 0; i <= n-k; i++)     {       int sum = 0;       for (int j = i; j < i+k; j++)       {         sum += arr[j];       }       if(sum < min){         min = sum;         minindex = i;       }      }     //printing the desired subarray     Console.Write("subarray with minimum average is: ");     for (int i = minindex; i < minindex+k; i++)     {       Console.Write(arr[i]+" ");     }     }    // Driver Code   static public void Main()   {     // Test Case 1     int[] arr = { 3, 7, 90, 20, 10, 50, 40};     int n = arr.Length;     int k=3;      // function call     findsubarrayleast(arr,k,n);   } }  // This code is contributed by Aarti_Rathi 
JavaScript
// javascript program code of Naive approach to // find subarray with minimum average  function findsubarrayleast(arr, k, n) {     var min = Number.MAX_VALUE;     var minindex = 0;     for (var i = 0; i < n - k; i++)     {         var sum = 0;         for (var j=i; j < i + k; j++)         {             sum += arr[j];         }         if (sum < min)         {             min = sum;             minindex = i;         }     }     // printing the desired subarray     console.log("subarray with minimum average is: ");     for (var i=minindex; i < minindex + k; i++)     {         console.log(arr[i] + " ");     } }      // Driver Code var arr = [3, 7, 90, 20, 10, 50, 40]; var n = arr.length; var k = 3;  // function call findsubarrayleast(arr, k, n);  // This code is contributed by Aarti_Rathi 

Output
subarray with minimum average is: 20 10 50 

Time Complexity: O(n*k) where n is the size of array.
Auxiliary Space: O(1)

An Efficient Solution is to solve the above problem in O(n) time and O(1) extra space. The idea is to use sliding window of size k. Keep track of sum of current k elements. To compute sum of current window, remove first element of previous window and add current element (last element of current window).

1) Initialize res_index = 0 // Beginning of result index 2) Find sum of first k elements. Let this sum be 'curr_sum' 3) Initialize min_sum = sum 4) Iterate from (k+1)'th to n'th element, do following    for every element arr[i]       a) curr_sum = curr_sum + arr[i] - arr[i-k]       b) If curr_sum < min_sum            res_index = (i-k+1) 5) Print res_index and res_index+k-1 as beginning and ending    indexes of resultant subarray.


Below is the implementation of above algorithm. 

C++
// A Simple C++ program to find minimum average subarray #include <bits/stdc++.h> using namespace std;  // Prints beginning and ending indexes of subarray // of size k with minimum average void findMinAvgSubarray(int arr[], int n, int k) {     // k must be smaller than or equal to n     if (n < k)         return;      // Initialize  beginning index of result     int res_index = 0;      // Compute sum of first subarray of size k     int curr_sum = 0;     for (int i = 0; i < k; i++)         curr_sum += arr[i];      // Initialize minimum sum as current sum     int min_sum = curr_sum;      // Traverse from (k+1)'th element to n'th element     for (int i = k; i < n; i++) {         // Add current item and remove first item of         // previous subarray         curr_sum += arr[i] - arr[i - k];          // Update result if needed         if (curr_sum < min_sum) {             min_sum = curr_sum;             res_index = (i - k + 1);         }     }      cout << "Subarray between [" << res_index << ", "          << res_index + k - 1 << "] has minimum average"; }  // Driver program int main() {     int arr[] = { 3, 7, 90, 20, 10, 50, 40 };     int k = 3; // Subarray size     int n = sizeof arr / sizeof arr[0];     findMinAvgSubarray(arr, n, k);     return 0; } 
Java
// A Simple Java program to find  // minimum average subarray  class Test {          static int arr[] = new int[] { 3, 7, 90, 20, 10, 50, 40 };      // Prints beginning and ending indexes of subarray     // of size k with minimum average     static void findMinAvgSubarray(int n, int k)     {         // k must be smaller than or equal to n         if (n < k)             return;          // Initialize beginning index of result         int res_index = 0;          // Compute sum of first subarray of size k         int curr_sum = 0;         for (int i = 0; i < k; i++)             curr_sum += arr[i];          // Initialize minimum sum as current sum         int min_sum = curr_sum;          // Traverse from (k+1)'th element to n'th element         for (int i = k; i < n; i++)          {             // Add current item and remove first             // item of previous subarray             curr_sum += arr[i] - arr[i - k];              // Update result if needed             if (curr_sum < min_sum) {                 min_sum = curr_sum;                 res_index = (i - k + 1);             }         }          System.out.println("Subarray between [" +                             res_index + ", " + (res_index + k - 1) +                             "] has minimum average");     }      // Driver method to test the above function     public static void main(String[] args)     {         int k = 3; // Subarray size         findMinAvgSubarray(arr.length, k);     } } 
Python3
# Python3 program to find # minimum average subarray  # Prints beginning and ending  # indexes of subarray of size k # with minimum average def findMinAvgSubarray(arr, n, k):      # k must be smaller than or equal to n     if (n < k): return 0      # Initialize beginning index of result     res_index = 0      # Compute sum of first subarray of size k     curr_sum = 0     for i in range(k):         curr_sum += arr[i]      # Initialize minimum sum as current sum     min_sum = curr_sum      # Traverse from (k + 1)'th     # element to n'th element     for i in range(k, n):              # Add current item and remove first          # item of previous subarray         curr_sum += arr[i] - arr[i-k]          # Update result if needed         if (curr_sum < min_sum):                      min_sum = curr_sum             res_index = (i - k + 1)              print("Subarray between [", res_index,           ", ", (res_index + k - 1),           "] has minimum average")  # Driver Code arr = [3, 7, 90, 20, 10, 50, 40] k = 3 # Subarray size n = len(arr) findMinAvgSubarray(arr, n, k)  # This code is contributed by Anant Agarwal. 
C#
// A Simple C# program to find  // minimum average subarray using System;  class Test {          static int[] arr = new int[] { 3, 7, 90, 20, 10, 50, 40 };      // Prints beginning and ending indexes of subarray     // of size k with minimum average     static void findMinAvgSubarray(int n, int k)     {         // k must be smaller than or equal to n         if (n < k)             return;          // Initialize beginning index of result         int res_index = 0;          // Compute sum of first subarray of size k         int curr_sum = 0;         for (int i = 0; i < k; i++)             curr_sum += arr[i];          // Initialize minimum sum as current sum         int min_sum = curr_sum;          // Traverse from (k+1)'th element to n'th element         for (int i = k; i < n; i++)          {             // Add current item and remove first item of             // previous subarray             curr_sum += arr[i] - arr[i - k];              // Update result if needed             if (curr_sum < min_sum) {                 min_sum = curr_sum;                 res_index = (i - k + 1);             }         }          Console.Write("Subarray between [" + res_index + ", " +                      (res_index + k - 1) +                       "] has minimum average");     }      // Driver method to test the above function     public static void Main()     {         int k = 3; // Subarray size         findMinAvgSubarray(arr.Length, k);     } }  // This code is contributed by nitin mittal. 
PHP
<?php // A Simple PHP program to find  // minimum average subarray  // Prints beginning and ending // indexes of subarray of size  // k with minimum average function findMinAvgSubarray($arr, $n, $k) {          // k must be smaller      // than or equal to n     if ($n < $k)         return;      // Initialize beginning      // index of result     $res_index = 0;      // Compute sum of first     // subarray of size k     $curr_sum = 0;     for ($i = 0; $i < $k; $i++)         $curr_sum += $arr[$i];      // Initialize minimum sum      // as current sum     $min_sum = $curr_sum;      // Traverse from (k+1)'th element     // to n'th element     for ( $i = $k; $i < $n; $i++)      {                  // Add current item and          // remove first item of         // previous subarray         $curr_sum += $arr[$i] - $arr[$i - $k];          // Update result if needed         if ($curr_sum < $min_sum) {             $min_sum = $curr_sum;             $res_index = ($i - $k + 1);         }     }      echo "Subarray between [" ,$res_index            , ", " ,$res_index + $k - 1, "] has minimum average"; }      // Driver Code     $arr = array(3, 7, 90, 20, 10, 50, 40);          // Subarray size     $k = 3;      $n = sizeof ($arr) / sizeof ($arr[0]);     findMinAvgSubarray($arr, $n, $k);     return 0;  // This code is contributed by nitin mittal. ?> 
JavaScript
<script>  // A Simple JavaScript program to find // minimum average subarray  // Prints beginning and ending indexes // of subarray of size k with minimum average function findMinAvgSubarray(arr, n, k) {          // k must be smaller than or equal to n     if (n < k)         return;      // Initialize beginning index of result     let res_index = 0;      // Compute sum of first subarray of size k     let curr_sum = 0;     for(let i = 0; i < k; i++)         curr_sum += arr[i];      // Initialize minimum sum as current sum     let min_sum = curr_sum;      // Traverse from (k+1)'th element     // to n'th element     for(let i = k; i < n; i++)      {                  // Add current item and remove first         // item of previous subarray         curr_sum += arr[i] - arr[i - k];          // Update result if needed         if (curr_sum < min_sum)         {             min_sum = curr_sum;             res_index = (i - k + 1);         }     }     document.write("Subarray between [" + res_index +                     ", " + (res_index + k - 1) +                     "] has minimum average"); }  // Driver code let arr = [ 3, 7, 90, 20, 10, 50, 40 ];  // Subarray size let k = 3;  let n = arr.length;  findMinAvgSubarray(arr, n, k);  // This code is contributed by Surbhi Tyagi.  </script> 

Output
Subarray between [3, 5] has minimum average


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


 


Next Article
Find the subarray with least average

K

kartik
Improve
Article Tags :
  • Mathematical
  • DSA
  • Arrays
  • Amazon
Practice Tags :
  • Amazon
  • Arrays
  • Mathematical

Similar Reads

    Javascript Program to Find the subarray with least average
    Given an array arr[] of size n and integer k such that k <= n.Examples : Input: arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3Output: Subarray between indexes 3 and 5The subarray {20, 10, 50} has the least average among all subarrays of size 3.Input: arr[] = {3, 7, 5, 20, -10, 0, 12}, k = 2Output: Sub
    3 min read
    Count of subarrays with average K
    Given an array arr[] of size N, the task is to count the number of subarrays having an average exactly equal to k.Examples:Input: arr[ ] = {1, 4, 2, 6, 10}, N = 5, K = 4Output: 3Explanation: The subarrays with an average equal to 4 are {4}, {2, 6}, {4, 2, 6}.Input: arr[ ] = {12, 5, 3, 10, 4, 8, 10,
    11 min read
    Count of subarrays of size K with average at least M
    Given an array arr[] consisting of N integers and two positive integers K and M, the task is to find the number of subarrays of size K whose average is at least M. Examples: Input: arr[] = {2, 3, 3, 4, 4, 4, 5, 6, 6}, K = 3, M = 4Output: 4Explanation:Below are the subarrays of size K(= 3) whose aver
    7 min read
    Smallest subarray with sum greater than a given value
    Given an array arr[] of integers and a number x, the task is to find the smallest subarray with a sum strictly greater than x.Examples:Input: x = 51, arr[] = [1, 4, 45, 6, 0, 19]Output: 3Explanation: Minimum length subarray is [4, 45, 6]Input: x = 100, arr[] = [1, 10, 5, 2, 7]Output: 0Explanation: N
    15+ min read
    Find maximum average subarray of k length
    Given an array with positive and negative numbers, find the maximum average subarray of the given length. Example: Input: arr[] = {1, 12, -5, -6, 50, 3}, k = 4Output: Maximum average subarray of length 4 begins at index 1.Maximum average is (12 - 5 - 6 + 50)/4 = 51/4Recommended PracticeMaximum avera
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

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