Find maximum sum taking every Kth element in the array

Given an array arr[] of integers and an integer K, the task is to find the maximum sum taking every Kth element i.e. sum = arr[i] + arr[i + k] + arr[i + 2 * k] + arr[i + 3 * k] + ……. arr[i + q * k] starting with any i.
Examples:Â
Input: arr[] = {3, -5, 6, 3, 10}, K = 3Â
Output: 10Â
All possible sequence are:Â
3 + 3 = 6Â
-5 + 10 = 5Â
6 = 6Â
3 = 3Â
10 = 10Input: arr[] = {3, 6, 4, 7, 2}, K = 2Â
Output: 13Â
Â
Naive Approach: The idea to solve this by using two nested loops and find the sum of every sequence starting from index i and sum every Kth element up to n, and find the maximum from all of these. The time complexity of this method will be O(N2)
Below is the implementation of the above approach:Â
Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the maximum sum for// every possible sequence such that// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]// is maximizedint maxSum(int arr[], int n, int K){Â
    // Initialize the maximum with    // the smallest value    int maximum = INT_MIN;Â
    // Find maximum from all sequences    for (int i = 0; i < n; i++) {Â
        int sumk = 0;Â
        // Sum of the sequence        // starting from index i        for (int j = i; j < n; j += K)            sumk = sumk + arr[j];Â
        // Update maximum        maximum = max(maximum, sumk);    }Â
    return maximum;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 3, 6, 4, 7, 2 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â Â Â Â int K = 2;Â
    cout << maxSum(arr, n, K);Â
    return (0);} |
Java
// Java implementation of the approachclass GFG{Â Â Â Â Â // Function to return the maximum sum for// every possible sequence such that// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]// is maximizedstatic int maxSum(int arr[], int n, int K){Â
    // Initialize the maximum with    // the smallest value    int maximum = Integer.MIN_VALUE;Â
    // Find maximum from all sequences    for (int i = 0; i < n; i++)     {Â
        int sumk = 0;Â
        // Sum of the sequence        // starting from index i        for (int j = i; j < n; j += K)            sumk = sumk + arr[j];Â
        // Update maximum        maximum = Math.max(maximum, sumk);    }Â
    return maximum;}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int arr[] = { 3, 6, 4, 7, 2 };Â Â Â Â int n = arr.length;Â Â Â Â int K = 2;Â
    System.out.println(maxSum(arr, n, K));}}Â
// This code is contributed by Code_Mech |
Python3
# Python 3 implementation of the approachimport sysÂ
# Function to return the maximum sum for# every possible sequence such that# a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]# is maximizeddef maxSum(arr, n, K):         # Initialize the maximum with    # the smallest value    maximum = -sys.maxsize - 1Â
    # Find maximum from all sequences    for i in range(n):        sumk = 0Â
        # Sum of the sequence        # starting from index i        for j in range(i, n, K):            sumk = sumk + arr[j]Â
        # Update maximum        maximum = max(maximum, sumk)Â
    return maximumÂ
# Driver codeif __name__ == '__main__':Â Â Â Â arr = [3, 6, 4, 7, 2]Â Â Â Â n = len(arr)Â Â Â Â K = 2Â Â Â Â print(maxSum(arr, n, K))Â Â Â Â Â # This code is contributed by# Surendra_Gangwar |
C#
// C# implementation of the approachusing System;Â
class GFG{Â Â Â Â Â // Function to return the maximum sum for// every possible sequence such that// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]// is maximizedstatic int maxSum(int []arr, int n, int K){Â
    // Initialize the maximum with    // the smallest value    int maximum = int.MinValue;Â
    // Find maximum from all sequences    for (int i = 0; i < n; i++)     {Â
        int sumk = 0;Â
        // Sum of the sequence        // starting from index i        for (int j = i; j < n; j += K)            sumk = sumk + arr[j];Â
        // Update maximum        maximum = Math.Max(maximum, sumk);    }Â
    return maximum;}Â
// Driver codepublic static void Main(){Â Â Â Â int []arr = { 3, 6, 4, 7, 2 };Â Â Â Â int n = arr.Length;Â Â Â Â int K = 2;Â
    Console.WriteLine(maxSum(arr, n, K));}}Â
// This code is contributed by Akanksha Rai |
PHP
<?php// PHP implementation of the approachÂ
// Function to return the maximum sum for// every possible sequence such that// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]// is maximizedfunction maxSum($arr, $n, $K){Â
    // Initialize the maximum with    // the smallest value    $maximum = PHP_INT_MIN;Â
    // Find maximum from all sequences    for ($i = 0; $i < $n; $i++)     {        $sumk = 0;Â
        // Sum of the sequence        // starting from index i        for ($j = $i; $j < $n; $j += $K)            $sumk = $sumk + $arr[$j];Â
        // Update maximum        $maximum = max($maximum, $sumk);    }Â
    return $maximum;}Â
// Driver code$arr = array(3, 6, 4, 7, 2);$n = sizeof($arr);$K = 2;Â
echo maxSum($arr, $n, $K);Â
// This code is contributed by Akanksha Rai?> |
Javascript
<script>Â
Â
// JavaScript implementation of the approachÂ
// Function to return the maximum sum for// every possible sequence such that// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]// is maximizedfunction maxSum(arr, n, K){Â
    // Initialize the maximum with    // the smallest value    var maximum = -1000000000;Â
    // Find maximum from all sequences    for (var i = 0; i < n; i++) {Â
        var sumk = 0;Â
        // Sum of the sequence        // starting from index i        for (var j = i; j < n; j += K)            sumk = sumk + arr[j];Â
        // Update maximum        maximum = Math.max(maximum, sumk);    }Â
    return maximum;}Â
// Driver codevar arr = [3, 6, 4, 7, 2];var n = arr.length;var K = 2;document.write( maxSum(arr, n, K));Â
Â
</script> |
13
Â
Time Complexity: O(N2) where N is the number of elements in array.
Auxiliary Space: O(1), no extra space required, so it is a constant.
Efficient Approach: This problem can be solved by using the concept of Suffix Arrays, we iterate the array from right side and store the suffix sum for each (i+k)’th element (ie., i+k < n) , and find the maximum sum. The time complexity of this method will be O(N).Â
Below is the implementation of the above approach.
Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the maximum sum for// every possible sequence such that// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]// is maximizedint maxSum(int arr[], int n, int K){Â
    // Initialize the maximum with    // the smallest value    int maximum = INT_MIN;Â
    // Initialize the sum array with zero    int sum[n] = { 0 };Â
    // Iterate from the right    for (int i = n - 1; i >= 0; i--) {Â
        // Update the sum starting at        // the current element        if (i + K < n)            sum[i] = sum[i + K] + arr[i];        else            sum[i] = arr[i];Â
        // Update the maximum so far        maximum = max(maximum, sum[i]);    }Â
    return maximum;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 3, 6, 4, 7, 2 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â Â Â Â int K = 2;Â
    cout << maxSum(arr, n, K);Â
    return (0);} |
Java
// Java implementation of the approachclass GFG {Â
    // Function to return the maximum sum for    // every possible sequence such that    // a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]    // is maximized    static int maxSum(int arr[], int n, int K)    {Â
        // Initialize the maximum with        // the smallest value        int maximum = Integer.MIN_VALUE;Â
        // Initialize the sum array with zero        int[] sum = new int[n];Â
        // Iterate from the right        for (int i = n - 1; i >= 0; i--) {Â
            // Update the sum starting at            // the current element            if (i + K < n)                sum[i] = sum[i + K] + arr[i];            else                sum[i] = arr[i];Â
            // Update the maximum so far            maximum = Math.max(maximum, sum[i]);        }Â
        return maximum;    }Â
    // Driver code    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));    }} |
Python
# Python implementation of the approachÂ
# Function to return the maximum sum for# every possible sequence such that # a[i] + a[i + k] + a[i + 2k] + ... + a[i + qk] # is maximizeddef maxSum(arr, n, K):         # Initialize the maximum with     # the smallest value    maximum = -2**32;Â
    # Initialize the sum array with zero    sum = [0]*nÂ
    # Iterate from the right    for i in range(n-1, -1, -1):                 # Update the sum starting at         # the current element        if( i + K < n ):            sum[i] = sum[i + K] + arr[i]        else:            sum[i] = arr[i];             # Update the maximum so far        maximum = max( maximum, sum[i] )         return maximum;Â
# Driver codearr = [3, 6, 4, 7, 2]n = len(arr);K = 2print(maxSum(arr, n, K)) |
C#
// C# implementation of the approachusing System;class GFG {Â
    // Function to return the maximum sum for    // every possible sequence such that    // a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]    // is maximized    static int maxSum(int[] arr, int n, int K)    {Â
        // Initialize the maximum with        // the smallest value        int maximum = int.MinValue;Â
        // Initialize the sum array with zero        int[] sum = new int[n];Â
        // Iterate from the right        for (int i = n - 1; i >= 0; i--) {Â
            // Update the sum starting at            // the current element            if (i + K < n)                sum[i] = sum[i + K] + arr[i];            else                sum[i] = arr[i];Â
            // Update the maximum so far            maximum = Math.Max(maximum, sum[i]);        }Â
        return maximum;    }Â
    // Driver code    public static void Main()    {        int[] arr = { 3, 6, 4, 7, 2 };        int n = arr.Length;        int K = 2;Â
        Console.Write(maxSum(arr, n, K));    }} |
PHP
<?php// PHP implementation of the approach// Function to return the maximum sum for// every possible sequence such that// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]// is maximizedfunction maxSum($arr, $n, $K){Â
    // Initialize the maximum with    // the smallest value    $maximum = PHP_INT_MIN;Â
    // Initialize the sum array with zero    $sum = array($n);Â
    // Iterate from the right    for ($i = $n - 1; $i >= 0; $i--)     {Â
        // Update the sum starting at        // the current element        if ($i + $K < $n)            $sum[$i] = $sum[$i + $K] + $arr[$i];        else            $sum[$i] = $arr[$i];Â
        // Update the maximum so far        $maximum = max($maximum, $sum[$i]);    }Â
    return $maximum;}Â
// Driver code{Â Â Â Â $arr = array(3, 6, 4, 7, 2 );Â Â Â Â $n = sizeof($arr);Â Â Â Â $K = 2;Â
    echo(maxSum($arr, $n, $K));}Â
// This code is contributed by Learner_ |
Javascript
<script>Â
// JavaScript implementation of the approachÂ
// Function to return the maximum sum for// every possible sequence such that// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]// is maximizedfunction maxSum(arr, n, K){Â
    // Initialize the maximum with    // the smallest value    var maximum = -1000000000;Â
    // Initialize the sum array with zero    var sum = Array(n).fill(0);Â
    // Iterate from the right    for (var i = n - 1; i >= 0; i--) {Â
        // Update the sum starting at        // the current element        if (i + K < n)            sum[i] = sum[i + K] + arr[i];        else            sum[i] = arr[i];Â
        // Update the maximum so far        maximum = Math.max(maximum, sum[i]);    }Â
    return maximum;}Â
// Driver codevar arr = [3, 6, 4, 7, 2 ];var n = arr.length;var K = 2;document.write( maxSum(arr, n, K));Â
Â
</script> |
13
Â
Time Complexity: O(N) where N is the number of elements in array.
Auxiliary Space: O(N), where N is the number of elements in array.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



