1862. Sum of Floored Pairs
UnknownView on LeetCode
Time: O(max log max)
Space: O(max)
Problem Overview
Sum of Floored Pairs (Unknown) asks you to solve a structured algorithmic task. This is a common Math / Binary Search pattern in coding interviews. Frequency prefix sums; for each value v iterate multiples k*v and add count[k*v] * k.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Frequency prefix sums; for each value v iterate multiples k*v and add count[k*v] * k.
Related patterns: Math, Binary Search, Dynamic Programming
1862.cs
C#
// Approach: Frequency prefix sums; for each value v iterate multiples k*v and add count[k*v] * k.
// Time: O(max log max) Space: O(max)
public class Solution
{
public int SumOfFlooredPairs(int[] nums)
{
const int kMod = 1000000007;
int kMax = nums.Max();
long ans = 0;
// count[i] := the number of `nums` <= i
int[] count = new int[kMax + 1];
foreach (var num in nums)
++count[num];
for (int i = 1; i <= kMax; ++i)
count[i] += count[i - 1];
for (int i = 1; i <= kMax; ++i)
{
if (count[i] > count[i - 1])
{
long sum = 0;
for (int j = 1; i * j <= kMax; ++j)
{
int lo = i * j - 1;
int hi = i * (j + 1) - 1;
sum += (count[Math.Min(hi, kMax)] - count[lo]) * (long)j;
}
ans += sum * (count[i] - count[i - 1]);
ans %= kMod;
}
}
return (int)ans;
}
}Was this solution helpful?
Related Problems
- 70. Climbing Stairs(Easy)
- 241. Different Ways to Add Parentheses(Medium)
- 264. Ugly Number II(Medium)
- 367. Valid Perfect Square(Unknown)
- 368. Largest Divisible Subset(Medium)
- 633. Sum of Square Numbers(Medium)