-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathNoob_sol
More file actions
64 lines (53 loc) · 1.53 KB
/
Copy pathNoob_sol
File metadata and controls
64 lines (53 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java .io.*;
class GFG {
// Returns beginning index
// of maximum average
// subarray of length 'k'
static int findMaxAverage(int []arr,
int n, int k)
{
// Check if 'k' is valid
if (k > n)
return -1;
// Create and fill array
// to store cumulative
// sum. csum[i] stores
// sum of arr[0] to arr[i]
int []csum = new int[n];
csum[0] = arr[0];
for (int i = 1; i < n; i++)
csum[i] = csum[i - 1] + arr[i];
// Initialize max_sm as
// sum of first subarray
int max_sum = csum[k - 1],
max_end = k - 1;
// Find sum of other
// subarrays and update
// max_sum if required.
for (int i = k; i < n; i++)
{
int curr_sum = csum[i] -
csum[i - k];
if (curr_sum > max_sum)
{
max_sum = curr_sum;
max_end = i;
}
}
// To avoid memory leak
//delete [] csum;
// Return starting index
return max_end - k + 1;
}
// Driver Code
static public void main (String[] args)
{
int []arr = {1, 12, -5, -6, 50, 3};
int k = 4;
int n = arr.length;
System.out.println("The maximum "
+ "average subarray of length "
+ k + " begins at index "
+ findMaxAverage(arr, n, k));
}
}