LeetCode周赛 + AcWing周赛(T4/T3)分析对比
AcWing 57 T3
Leetcode 双周赛80 T4
前言
两道题之间的共同点在于子数组价值的定义,LC为子数组的和乘上其长度,AcWing为子数组的和除上其长度(平均值)。
分析 - AcWing T3
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 1000010;
int n;
LL s[N];
int stk[N];
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i ++)
{
int x;
scanf("%d", &x);
s[i] = s[i - 1] + x - 100;
}
int top = 0,res = 0;
stk[++ top] = 0;
for(int i = 1; i <= n; i ++)
{
if(s[stk[top]] > s[i]) stk[++ top] = i;
else if(s[stk[top]] < s[i])
{
int l = 0, r = top;
while(l < r)
{
int mid = l + r >> 1;
if(s[stk[mid]] < s[i]) r = mid;
else l = mid + 1;
}
res = max(res, i - stk[r]);
}
}
printf("%d\n", res);
return 0;
}
分析 - LeetCode T4
class Solution {
public:
typedef long long LL;
long long countSubarrays(vector<int>& nums, long long k) {
LL res = 0, sum = 0;
for(int i = 0, j = 0; j < nums.size(); j ++)
{
sum += nums[j];
while(sum * (j - i + 1) >= k) sum -= nums[i ++];
res += j - i + 1;
}
return res;
}
};