Easy題的意義是一定要思維縝密。
比如,nums[]有可能是負數,那max的初值就不能是0;
另外,計算完成后total要置0,要么就把total拿到for里面去。
Brute Force
public double findMaxAverage(int[] nums, int k) {
double max = Integer.MIN_VALUE;
int total = 0;
for (int i = 0; i < nums.length + 1 - k; i++) {
for (int count = 0; count < k; count++) {
total += nums[i + count];
}
max = Math.max(max, total / (double) k);
total = 0 ;
}
return max;
}
Sliding Window
邊界條件最好舉例子帶進去不然會錯。
public double findMaxAverage(int[] nums, int k) {
//sliding window
int total = 0;
for (int i = 0; i < k; i++) {
total += nums[i];
}
double max = total / (double) k;
for (int i = 1; i < nums.length - k + 1; i++) {
total = total - nums[i - 1];
total = total + nums[i + k - 1];
max = Math.max(total / (double) k, max);
}
return max;
}