Maximum Product of Subarray of Size K
This program finds maximum product of subarray of fixed size K.
Problem Statement
Write a Java program to find maximum product of subarray of size 3.
Source Code
| 1 | public class MaxProductSubarrayK { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Max Product Subarray of Size K"); |
| 4 | int[] arr = {1,2,3,4,5}; |
| 5 | int k=3, prod=1; |
| 6 | for(int i=0;i<k;i++) prod*=arr[i]; |
| 7 | int maxProd=prod; |
| 8 | for(int i=k;i<arr.length;i++){ |
| 9 | prod=prod/arr[i-k]*arr[i]; |
| 10 | maxProd=Math.max(maxProd,prod); |
| 11 | } |
| 12 | System.out.println("Maximum product subarray of size "+k+" = "+maxProd); |
| 13 | } |
| 14 | } |
Program Output
Eduinq Max Product Subarray of Size K Maximum product subarray of size 3 = 60
Explanation
Initial product calculated for first window. - Sliding window updates product efficiently. - Maximum product tracked. - Together demonstrates fixed size subarray product calculation. Conclusion: Shows how to find maximum product of subarray of size K.