2024/10/11 灵茶题单 滑动窗口
This commit is contained in:
parent
7a5bb341a1
commit
7baab96a2b
|
@ -0,0 +1,56 @@
|
|||
package com.cool.ling_cha_mount.sliding_windows;
|
||||
|
||||
/**
|
||||
* Created with IntelliJ IDEA.
|
||||
*
|
||||
* @Author: Cool
|
||||
* @Date: 2024/10/11/20:12
|
||||
* @Description: 1423. 可获得的最大点数
|
||||
* Level 4
|
||||
* Score 1574
|
||||
* Hard 2
|
||||
*/
|
||||
public class Num1423 {
|
||||
|
||||
/**
|
||||
* @Author Cool
|
||||
* @Date 20:19 2024/10/11
|
||||
* 反向思维
|
||||
**/
|
||||
public int maxScore(int[] cardPoints, int k) {
|
||||
int sum = 0;
|
||||
int allSum =0;
|
||||
int len = cardPoints.length;
|
||||
int res = Integer.MAX_VALUE;
|
||||
for (int i = 0; i < len - k; i++) {
|
||||
allSum+=cardPoints[i];
|
||||
sum += cardPoints[i];
|
||||
}
|
||||
res = Math.min(sum, res);
|
||||
for (int i = len - k; i < len; i++) {
|
||||
sum += cardPoints[i];
|
||||
allSum+=cardPoints[i];
|
||||
sum -= cardPoints[i - (len - k)];
|
||||
res = Math.min(sum, res);
|
||||
}
|
||||
return allSum - res;
|
||||
}
|
||||
/**
|
||||
* @Author Cool
|
||||
* @Date 20:19 2024/10/11
|
||||
* 正向思维
|
||||
**/
|
||||
public int maxScore1(int[] cardPoints, int k) {
|
||||
int sum=0;
|
||||
for(int i=0;i<k;i++){
|
||||
sum+=cardPoints[i];
|
||||
}
|
||||
int res=Math.max(0,sum);
|
||||
for(int i=0;i<k;i++){
|
||||
sum+=cardPoints[cardPoints.length-i-1];
|
||||
sum-=cardPoints[k-i-1];
|
||||
res=Math.max(res,sum);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue