-2

Given an integer array and size of subarray, find the first subarray with leat average in single loop. Print first index of subarray and average. Problem is I can't use variable substring length c without using any additional loop. My code is-

public void FindFirstSub(int a[], int b, int c)
{
    int average=0,sum=0,leastav=0;
    for(int i=0;i<a.length-c;i++)
    {
        sum = 0;
        sum = a[i]+a[i+1]+a[i+2]; // Here is problem.
        System.out.print(a[i]+" "+a[i+1]+" "+a[i+2]+"\n");
        average = sum/c;
        if(leastav==0)
            leastav=average;
        else if(leastav>average)
            leastav=average;
    }
    System.out.println("Least average is "+leastav);
}
theduck
  • 2,589
  • 13
  • 17
  • 23

2 Answers2

0

You need to set sum to 0 outside of your for loop and keep a running total for sum. With every iteration, subtract the first element of the previous sub-array while adding the new last element of the new sub-array. You shouldn't start subtracting till you reach your second sub-array or checking for averages until 'i' is the last index of the first sub-array.

0

You can't use the single loop only to find the least average but complexity you can maintain till O(n).

        static void FindFirstSub(int arr[],int n, int k) 
            { 
              if (n < k) 
                 return; 

            int res_index = 0; 

            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; 

            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 btw [" + 
                                res_index + ", " + (res_index + k - 1) + 
                                "] has minimum average"); 
        } 

        // Driver method to test the above function 
        public static void main(String[] args) 
        {   
            int arr[] = { 3, 7, 90, 20, 10, 50, 40 }; 
            int k = 3; // Subarray size 
           FindFirstSub(arr.length, k); 
        }