classSolution {publicintdietPlanPerformance(int[] calories,int k,int lower,int upper) {int points =0;int sum =0;for (int i =0; i < k; i++) { sum += calories[i]; }if (sum < lower) points--;if (sum > upper) points++;for (int i = k; i <calories.length; i++) { sum += calories[i] - calories[i-k];if (sum < lower) points--;if (sum > upper) points++; }return points; }}
one for loop
classSolution {// 0 1 2publicintdietPlanPerformance(int[] calories,int k,int lower,int upper) {int points =0;int sum =0;for (int i =0; i <calories.length; i++) { sum += calories[i];if (i >= k) { // when have over k sum, have a new sliding window sum sum -= calories[i-k]; }if (i >= k-1) { // when have k sum, start to calculate pointsif (sum < lower) points--;if (sum > upper) points++; } }return points; }}