-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2090_K_Radius_Subarray_Averages.java
56 lines (42 loc) · 1.17 KB
/
2090_K_Radius_Subarray_Averages.java
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
/*
* 2090. K Radius Subarray Averages
* Problem Link: https://leetcode.com/problems/k-radius-subarray-averages/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public int[] getAverages(int[] nums, int k) {
int subArraySize = 2 * k + 1;
int n = nums.length;
// create a result array
int [] result = new int[n];
int i = 0;
long sum = 0;
while ( i < k && i < n) {
result[i] = -1;
sum += nums[i];
i++;
}
// add k more elements to the sum
for (int j = i; j < k+i && j < n; j++) {
sum += nums[j];
}
while (i+k<n) {
// add the rightmost element
sum += nums[i+k];
result[i] = (int)(sum/subArraySize);
// remove element from left
sum -= nums[i-k];
i++;
}
while ( i < n) {
result [i] = -1;
i++;
}
return result;
}
}