---
# System prepended metadata

title: How to split an array into K subarrays
tags: [Issue]

---

# How to split an array into K subarrays
###### tags: `Issue`

* Tutorial:\
1. C++ only with vector STL
https://www.youtube.com/watch?v=kbEvi_jEtmQ&ab_channel=MiketheCoder

2. Using python with toolkit
https://stackoverflow.com/questions/9088321/show-all-possible-groupings-of-a-list-given-only-the-amount-of-sublists-length


```cpp=
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
int ans = 100000000;
// the answer is stored in ans
// we call this function solve
// max function is used to find max of two elements
int max(int a, int b) { return a > b ? a : b; }
// min function is used to find min of two elements
int min(int a, int b) { return a < b ? a : b; }
void divider(int a[], int n, int k, int index, int pre_sum)
{
    // K=1 is the base Case
    if (k == 1)
    {
        // maxsum = max(maxsum, sum);
        int last = 0;
        for (int i = index; i < n; i++)
        {
            last += a[i];
        }
        int maxsum = pre_sum + last * (n - index);
        // we update maxsum
        // maxsum = max(maxsum, sum);
        // the answer is stored in ans
        ans = min(ans, maxsum);
        return;
    }
    int sum = 0;
    // using for loop to divide the array into K-subarray
    for (int i = index; i < n; i++)
    {
        sum += a[i];
        int proportion = sum * (i - index + 1);
        // for each subarray we calculate sum ans update
        // maxsum
        // maxsum = max(maxsum, sum);
        // calling function again
        divider(a, n, k - 1, i + 1, proportion + pre_sum);
    }
}
// Driver Code
int main()
{
    int arr[] = {1, 3, 2, 4};
    int k; // K divisions
    std::cin >> k;
    int n = 4; // Size of Array
    solve(arr, n, k, 0, 0);
    printf("ans = %d", ans);
}

```