Maximum subsequence sum such that all elements are K distance apart | Function to return the maximum subarray sum for the array { a [ i ] , a [ i + k ] , a [ i + 2 k ] , ... } ; Function to return the sum of the maximum required subsequence ; To store the result ; Run a loop from 0 to k ; Find the maximum subarray sum for the array { a [ i ] , a [ i + k ] , a [ i + 2 k ] , ... } ; Return the maximum value ; Driver code
function maxSubArraySum ( a , n , k , i ) { let max_so_far = Number . MIN_VALUE , max_ending_here = 0 ; while ( i < n ) { max_ending_here = max_ending_here + a [ i ] ; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; if ( max_ending_here < 0 ) max_ending_here = 0 ; i += k ; } return max_so_far ; } function find ( arr , n , k ) { let maxSum = 0 ; for ( let i = 0 ; i <= Math . min ( n , k ) ; i ++ ) { let sum = 0 ; maxSum = Math . max ( maxSum , maxSubArraySum ( arr , n , k , i ) ) ; } return maxSum ; } let arr = [ 2 , - 3 , - 1 , - 1 , 2 ] ; let n = arr . length ; let k = 2 ; document . write ( find ( arr , n , k ) ) ;