Java Exercises: Find the total number of continuous subarrays in a specified array of integers
Java Basic: Exercise-203 with Solution
Write a Java program to find the contiguous subarray of given length k which has the maximum average value of a given array of integers. Display the maximum average value.
Example:
Original Array: [4, 2, 3, 3, 7, 2, 4]
Value of k: 3
Maximum average value : 4.333333333333333
Pictorial Presentation:

Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] nums = {4,2,3,3,7,2,4};
int k = 3;
System.out.print("Original Array: "+Arrays.toString(nums));
System.out.print("\nValue of k: "+k);
System.out.print("\nMaximum average value: "+find_max_average(nums, k));
}
public static double find_max_average(int[] nums, int k) {
int sum = 0;
for (int i = 0; i < k; i++) {
sum += nums[i];
}
int max_val = sum;
for (int i = k; i < nums.length; i++) {
sum = sum - nums[i - k] + nums[i];
max_val = Math.max(max_val, sum);
}
return (double) max_val / k;
}
}
Sample Output:
Original Array: [4, 2, 3, 3, 7, 2, 4] Value of k: 3 Maximum average value: 4.333333333333333
Flowchart:

Java Code Editor:
Company: Google
Contribute your code and comments through Disqus.
Previous: Write a Java program to find the total number of continuous subarrays in a given array of integers whose sum equals to an given integer.
Next: Write a Java program to compute xn % y where x, y and n are all 32bit integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
Java: ConvertInputStreamToString
Converts InputStream to a String.
public static String convertInputStreamToString(final InputStream in) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString(StandardCharsets.UTF_8.name()); }
Ref: https://bit.ly/2N1GDss
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises