Sum of all odd length subarrays | Java program for the above approach ; Function to calculate the sum of all odd length subarrays ; Stores the sum ; Size of array ; Traverse the array ; Generate all subarray of odd length ; Add the element to sum ; Return the final sum ; Driver Code ; Given array arr [ ] ; Function call
import java . io . * ; import java . util . Arrays ; class GFG { static int OddLengthSum ( int [ ] arr ) { int sum = 0 ; int l = arr . length ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = i ; j < l ; j += 2 ) { for ( int k = i ; k <= j ; k ++ ) { sum += arr [ k ] ; } } } return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 5 , 3 , 1 , 2 } ; System . out . print ( OddLengthSum ( arr ) ) ; } }