java: add «643. Maximum Average Subarray I»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
8c0c14f406
commit
4b297be824
1 changed files with 21 additions and 0 deletions
21
java/maximum-average-subarray-i.java
Normal file
21
java/maximum-average-subarray-i.java
Normal file
|
@ -0,0 +1,21 @@
|
|||
class Solution {
|
||||
private long sumFirst(int[] nums, int k) {
|
||||
long sum = 0;
|
||||
for (var i = 0; i < k; ++i) {
|
||||
sum += nums[i];
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public double findMaxAverage(int[] nums, int k) {
|
||||
var runningSum = sumFirst(nums, k);
|
||||
var foundMax = runningSum;
|
||||
|
||||
for (var i = k; i < nums.length; ++i) {
|
||||
runningSum += nums[i] - nums[i - k];
|
||||
foundMax = Math.max(foundMax, runningSum);
|
||||
}
|
||||
|
||||
return (double) foundMax / k;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue