Leetcode solution 1176: Diet Plan Performance
Problem Statement?A dieter consumes? Given an integer?
Initially,the dieter has zero points. Return the total number of points the dieter has after dieting for? Note that the total points can be negative. ? Example 1: Input: calories = [1,2,3,4,5],k = 1,lower = 3,upper = 3
Output: 0 Explanation: Since k = 1,we consider each element of the array separately and compare it to lower and upper. calories[0] and calories[1] are less than lower so 2 points are lost. calories[3] and calories[4] are greater than upper so 2 points are gained.
Example 2: Input: calories = [3,2],k = 2,lower = 0,upper = 1
Output: 1 Explanation: Since k = 2,we consider subarrays of length 2. calories[0] + calories[1] > upper so 1 point is gained.
Example 3: Input: calories = [6,5,0],lower = 1,upper = 5
Output: 0 Explanation: calories[0] + calories[1] > upper so 1 point is gained. lower <= calories[1] + calories[2] <= upper so no change in points. calories[2] + calories[3] < lower so 1 point is lost.
? Constraints:
Problem link ?Video TutorialYou can find the detailed video tutorial here
? Thought ProcessThis is an easy problem but might be a bit hard to code it up correctly in one pass. We can use a sliding window to keep a rolling sum and compare it with upper and lower bound. ? A few caveats in implementation:
? Solutions?Sliding window1 public int dietPlanPerformance(int[] calories,int k,int lower,int upper) { 2 if (calories == null || calories.length == 0) { 3 return 0; 4 } 5 6 int rollingSum = 0; 7 int performance = 0; 8 9 for (int i = 0; i < calories.length; i++) { 10 // always adding element to the sliding window on the right 11 rollingSum += calories[i]; 12 // initial value 13 if (i < k - 1) { 14 continue; 15 } 16 17 // when to pop out element on the left 18 if (i >= k) { 19 rollingSum -= calories[i - k]; 20 } 21 if (rollingSum > upper) { 22 performance++; 23 } 24 if (rollingSum < lower) { 25 performance--; 26 } 27 } 28 29 return performance; 30 } ? ? Time Complexity: O(N) visited the array once Space Complexity: O(1) No extra space is needed ? References
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- java – 在ZonedDateTime或Instant中将小时分和秒
- 不依赖于任何Java类库的中文转拼音实现
- java – 绘制一个在下一个绘画中不会消失的矩形
- Struts2 ActionContext.getSession()法:获取ses
- Java if()不起作用
- java – 在Spark中,是否可以在两个执行程序之间共
- Debugging to Understand Finalizer--reference
- java – 仙人掌与模拟对象(jMock,Easy mock)
- java – 为什么使用maven shade插件重定位不起作
- java – Android – 异步网络调用 – 响应相互依