Maximum circular subarray sum of size K

Given an array arr of size N and an integer K, the task is to find the maximum sum subarray of size k among all contiguous sub-array (considering circular subarray also).

Examples:

Input: arr = {18, 4, 3, 4, 5, 6, 7, 8, 2, 10}, k = 3
Output:
max circular sum = 32
start index = 9
end index = 1
Explanation:
Maximum Sum = 10 + 18 + 4 = 32

Input: arr = {8, 2, 5, 9}, k = 4
Output:
max circular sum = 24
start index = 0
end index = 3

Approach:



  • Iterate the loop till (n + k) times and
  • Take (i % n) to handle the case when the array index becomes greater than n.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find maximum circular
// subarray sum of size k
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to calculate
// maximum sum
void maxCircularSum(int arr[], int n, int k)
{
    // k must be greater
    if (n < k) {
        cout << "Invalid";
        return;
    }
  
    int sum = 0, start = 0, end = k - 1;
  
    // calculate the sum of first k elements.
    for (int i = 0; i < k; i++) {
        sum += arr[i];
    }
  
    int ans = sum;
  
    for (int i = k; i < n + k; i++) {
  
        // add current element to sum
        // and subtract the first element
        // of the previous window.
        sum += arr[i % n] - arr[(i - k) % n];
  
        if (sum > ans) {
            ans = sum;
            start = (i - k + 1) % n;
            end = i % n;
        }
    }
  
    cout << "max circular sum = "
         << ans << endl;
    cout << "start index = " << start
         << "\nend index = " << end << endl;
}
  
// Driver Code
int main()
{
    int arr[] = { 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
  
    maxCircularSum(arr, n, k);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find maximum circular 
// subarray sum of size k
  
import java.util.*;
  
class GFG
{
  
    // Function to calculate
    // maximum sum
    static void maxCircularSum(int[] arr, int n, int k) 
    {
  
        // k must be greater
        if (n < k) 
        {
            System.out.println("Invalid");
            return;
        }
  
        int sum = 0, start = 0, end = k - 1;
  
        // calculate the sum of first k elements.
        for (int i = 0; i < k; i++)
            sum += arr[i];
  
        int ans = sum;
  
        for (int i = k; i < n + k; i++) 
        {
  
            // add current element to sum
            // and subtract the first element
            // of the previous window.
            sum += arr[i % n] - arr[(i - k) % n];
  
            if (sum > ans) 
            {
                ans = sum;
                start = (i - k + 1) % n;
                end = i % n;
            }
        }
  
        System.out.println("max circular sum = " + ans);
        System.out.println("start index = " + start + "\nend index = " + end);
    }
  
    // Driver Code
    public static void main(String[] args) 
    {
        int[] arr = { 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 };
        int n = arr.length;
        int k = 3;
  
        maxCircularSum(arr, n, k);
    }
}
  
// This code is contributed by
// sanjeev2552

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find maximum circular 
# subarray sum of size k 
  
# Function to calculate 
# maximum sum 
def maxCircularSum(arr, n, k) :
  
    # k must be greater 
    if (n < k) :
        print("Invalid"); 
        return
  
    sum = 0; start = 0; end = k - 1
  
    # calculate the sum of first k elements. 
    for i in range(k) :
        sum += arr[i]; 
  
    ans = sum
  
    for i in range(k, n + k) :
  
        # add current element to sum 
        # and subtract the first element 
        # of the previous window. 
        sum += arr[i % n] - arr[(i - k) % n]; 
  
        if (sum > ans) :
            ans = sum
            start = (i - k + 1) % n; 
            end = i % n; 
  
    print("max circular sum = ",ans); 
    print("start index = ", start, 
          "\nend index = ", end); 
  
# Driver Code 
if __name__ == "__main__"
  
    arr = [ 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 ]; 
    n = len(arr); 
    k = 3
  
    maxCircularSum(arr, n, k); 
  
# This code is contributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find maximum circular 
// subarray sum of size k
using System;
  
class GFG
{
  
    // Function to calculate
    // maximum sum
    static void maxCircularSum(int[] arr, 
                               int n, int k) 
    {
  
        // k must be greater
        if (n < k) 
        {
            Console.WriteLine("Invalid");
            return;
        }
  
        int sum = 0, start = 0, end = k - 1;
  
        // calculate the sum of first k elements.
        for (int i = 0; i < k; i++)
            sum += arr[i];
  
        int ans = sum;
  
        for (int i = k; i < n + k; i++) 
        {
  
            // add current element to sum
            // and subtract the first element
            // of the previous window.
            sum += arr[i % n] - arr[(i - k) % n];
  
            if (sum > ans) 
            {
                ans = sum;
                start = (i - k + 1) % n;
                end = i % n;
            }
        }
  
        Console.WriteLine("max circular sum = " + ans);
        Console.WriteLine("start index = " + start +
                          "\nend index = " + end);
    }
  
    // Driver Code
    public static void Main(String[] args) 
    {
        int[] arr = { 18, 4, 3, 4, 5, 
                      6, 7, 8, 2, 10 };
        int n = arr.Length;
        int k = 3;
  
        maxCircularSum(arr, n, k);
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

max circular sum = 32
start index = 9
end index = 1

Time Complexity:O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.