# 查找k個長度的最大平均子數組

## 例

`arr[] = {1,3,12,34,76,10}`
`[2, 4]`

`arr[] = {1,-2,8,3,-6,9}`
`[1, 3]`

## 查找k個長度的最大平均子數組的算法

```1. Declare a currentSum.
2. Set the currentSum to arr[0].
3. Traverse the array from i=1 to less than the length of n.
Store and update the addition of currentSum and arr[i] into the currentSum.
4. Set maximumSum to currentSum.
5. Set END to k-1.
6. Traverse the array from i=k to k to i < n.
7. Set sum to sum + arr[i] - arr[i - k].
Check if the sum is greater than maximumSum.
1. Set sum to maximumSum.
2. Set END to i.
8. Return END – k + 1.```

## 查找k個長度的最大平均子數組的代碼

### C ++代碼

```#include<iostream>
using namespace std;
int getMaxAvgSubArray(int arr[], int n, int k)
{
if (k > n)
return -1;
int currentSum;
currentSum = arr[0];
for (int i = 1; i < n; i++)
currentSum = currentSum + arr[i];
int maximumSum = currentSum;
int END = k - 1;
for (int i = k; i < n; i++)
{
currentSum = currentSum + arr[i] - arr[i-k];
if (currentSum > maximumSum)
{
maximumSum = currentSum;
END = i;
}
}
return END - k + 1;
}
int main()
{
int arr[] = {1,3,12,34,76,10};
int k = 3;
int n = sizeof(arr)/sizeof(arr[0]);
int start=getMaxAvgSubArray(arr, n, k);
cout<<"Maximum average subarray: ["<< start<<" "<< (start + k - 1)<<"]";
return 0;
}```
`Maximum average subarray: [2 4]`

### Java代碼

```class MaximumAverageSubarray
{
public static int getMaxAvgSubArray(int []arr,int n, int k)
{
if (k > n)
return -1;

int currentSum = arr[0];

for (int i = 1; i < k; i++)
currentSum = currentSum + arr[i];

int maximumSum = currentSum;
int END = k - 1;

for (int i = k; i < n; i++)
{
currentSum = currentSum + arr[i] - arr[i-k];

if (currentSum > maximumSum)
{
maximumSum = currentSum;
END = i;
}
}
return END - k + 1;
}
public static void main (String[] args)
{
int []arr = {1,3,12,34,76,10};
int k = 3;
int n = arr.length;
int start=getMaxAvgSubArray(arr, n, k);
System.out.println("Maximum average subarray: ["+start+" "+ (start + k - 1)+"]");
}
}
```
`Maximum average subarray: [2 4]`