题目链接: Leetcode Weekly Contest 271
1、2103. Rings and Rods
难度:Easy
代码:
class Solution {
public int countPoints(String rings) {
int[][] colorCount=new int[10][3];
char[] s=rings.toCharArray();
for(int i=0;i<s.length/2;i++){
char color=s[2*i];
int rod=s[2*i+1]-'0';
if(color=='R'){
colorCount[rod][0]++;
}
else if(color=='G'){
colorCount[rod][1]++;
}
else{
colorCount[rod][2]++;
}
}
int res=0;
for(int i=0;i<colorCount.length;i++){
if(colorCount[i][0]>0&&colorCount[i][1]>0&&colorCount[i][2]>0){
res++;
}
}
return res;
}
}
2、2104. Sum of Subarray Ranges
难度:Medium
代码:
class Solution {
public long subArrayRanges(int[] nums) {
int n=nums.length;
long[][] range=new long[n][n];
long sum=0;
for(int i=0;i<n;i++){
int max=nums[i];
int min=nums[i];
for(int j=i;j<n;j++){
if(nums[j]>max){
max=nums[j];
}
if(nums[j]<min){
min=nums[j];
}
range[i][j]=max-min;
sum+=range[i][j];
}
}
return sum;
}
}
3、2105. Watering Plants II
难度:Medium
思路:
模拟。
代码
class Solution {
public int minimumRefill(int[] plants, int capacityA, int capacityB) {
int n=plants.length;
int l=0,r=n-1;
int A=capacityA,B=capacityB;
int res=0;
while(l<r){
if(A>=plants[l]){
A-=plants[l];
}
else{
res++;
A=capacityA;
A-=plants[l];
}
if(B>=plants[r]){
B-=plants[r];
}
else{
res++;
B=capacityB;
B-=plants[r];
}
l++;
r--;
}
if(l==r){
if(Math.max(A,B)<plants[l]){
res++;
}
}
return res;
}
}
4、2106. Maximum Fruits Harvested After at Most K Steps
难度:Hard
思路
贪心+前缀和,要么先往左再往右,要么先往右再往左,可以k步的走法。
代码
class Solution {
public int maxTotalFruits(int[][] fruits, int startPos, int k) {
int len=200001;
int[] nums=new int[len];
for(int[] arr:fruits){
int pos=arr[0];
int amount=arr[1];
if(pos>=0&&pos<len){
nums[pos]=amount;
}
}
int n=nums.length;
int[] prefix=new int[n+1];
for(int i=1;i<prefix.length;i++){
prefix[i]=prefix[i-1]+nums[i-1];
}
int res=0;
for(int i=0;i<=k;i++){//先向左边走
int sum=0;
int l=Math.max(startPos-i,0);//i表示向左边走几步,l是左边界
sum+=(prefix[startPos+1]-prefix[l]);
int r=startPos+(k-2*(startPos-l));
if(r>startPos){
r=Math.min(r,len-1);
sum+=(prefix[r+1]-prefix[startPos+1]);
}
res=Math.max(res,sum);
}
for(int i=0;i<=k;i++){//先向右边走
int sum=0;
int r=Math.min(startPos+i,len-1);//i表示向左边走几步,l是左边界
sum+=(prefix[r+1]-prefix[startPos]);
int l=startPos-(k-2*(r-startPos));
if(l<startPos){
l=Math.max(0,l);
sum+=(prefix[startPos-1+1]-prefix[l]);
}
res=Math.max(res,sum);
}
return res;
}
}