题目链接: Leetcode Weekly Contest 240
写在前面:
本次周赛做出了前两道。
1、1854. Maximum Population Year
难度:Easy
题目大意:
给出若干个人的出身年份与死亡年份,求人口最多那一年的人数。
思路:
思路1:
暴力求解
思路2:
参考高赞回答,线性扫描,使用前缀和来进行求解。
代码
思路1代码;
class Solution {
public int maximumPopulation(int[][] logs) {
int[] population=new int[101];
for(int[] year:logs){
for(int i=year[0]-1950;i<year[1]-1950;i++){
population[i]++;
}
}
int maxPopulation=population[0];
int res=0;
for(int i=0;i<population.length;i++){
if(population[i]>maxPopulation){
maxPopulation=population[i];
res=i;
}
}
return res+1950;
}
}
思路2代码;
class Solution {
public int maximumPopulation(int[][] logs) {
int[] population=new int[101];
for(int[] year:logs){
population[year[0]-1950]++;
population[year[1]-1950]--;
}
int maxPopulation=population[0];
int res=0;
for(int i=1;i<population.length;i++){
population[i]+=population[i-1];
if(population[i]>maxPopulation){
maxPopulation=population[i];
res=i;
}
}
return res+1950;
}
}
2、1838. Frequency of the Most Frequent Element
难度:Medium
题目大意:
详见题意。
思路:
两个数组都是有序的,用双指针。
代码
class Solution {
public int maxDistance(int[] nums1, int[] nums2) {
int res=0;
int j=-1;
for(int i=0;i<nums1.length;i++){
while(j+1<nums2.length&&nums1[i]<=nums2[j+1]){
j++;
}
res=Math.max(res,j-i);
}
return res;
}
}
3、1856. Maximum Subarray Min-Product
难度:Medium
题目大意:
详见题目。
思路:
与leetcode 84. Largest Rectangle in Histogram思路类似。
代码
class Solution {//与leetcode84思路类似
public int maxSumMinProduct(int[] nums) {
int n=nums.length;
long[] prefixSum=new long[n+1];
prefixSum[0]=0;
for(int i=1;i<n+1;i++){
prefixSum[i]=prefixSum[i-1]+nums[i-1];
}
int[] lessFromLeft=new int[n];//lessFromLeft[i]表示从下标i往左找,第一个比height[i]小的元素的下标
int[] lessFromRight=new int[n];
lessFromLeft[0]=-1;
lessFromRight[n-1]=n;
for(int i=1;i<n;i++){
int p=i-1;
while(p>=0&&nums[p]>=nums[i]){
p=lessFromLeft[p];
//因为height[p]>=heights[i],所以直接跳到p=lessFromLeft[p],再进行判断。中间的元素>=heights[p]>=heights[i]
}
lessFromLeft[i]=p;
}
for(int i=n-2;i>=0;i--){
int p=i+1;
while(p<=n-1&&nums[p]>=nums[i]){
p=lessFromRight[p];
}
lessFromRight[i]=p;
}
long maxArea=0;
for(int i=0;i<n;i++){
int l=lessFromLeft[i],r=lessFromRight[i];
long area=nums[i]*(prefixSum[r]-prefixSum[l+1]);
if(area>maxArea){
maxArea=area;
}
}
return (int)(maxArea%1000000007);
}
}
4、1857. Largest Color Value in a Directed Graph
难度:Hard
题目大意:
详见题目。
思路
暂时不会
代码
//