Find maximum sum taking every Kth element in the array | Java implementation of the approach ; Function to return the maximum sum for every possible sequence such that a [ i ] + a [ i + k ] + a [ i + 2 k ] + ... + a [ i + qk ] is maximized ; Initialize the maximum with the smallest value ; Initialize the sum array with zero ; Iterate from the right ; Update the sum starting at the current element ; Update the maximum so far ; Driver code
class GFG { static int maxSum ( int arr [ ] , int n , int K ) { int maximum = Integer . MIN_VALUE ; int [ ] sum = new int [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i + K < n ) sum [ i ] = sum [ i + K ] + arr [ i ] ; else sum [ i ] = arr [ i ] ; maximum = Math . max ( maximum , sum [ i ] ) ; } return maximum ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 6 , 4 , 7 , 2 } ; int n = arr . length ; int K = 2 ; System . out . print ( maxSum ( arr , n , K ) ) ; } }