貪心的思想:查詢次數最多的數,搭配最大的數,和最大。優化
直接作的話,掃描區間時間複雜度是O(n^2)超時3d
class Solution { public: const int mod = (int)1e9+7; int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) { sort(nums.begin(),nums.end()); unordered_map<int,int> hashmap; for(auto request:requests){ for(int i=request[0];i<=request[1];i++){ hashmap[i]++; } } vector<pair<int,int>> v; for(auto p:hashmap){ v.push_back({p.second,p.first}); } sort(v.begin(),v.end()); int n = v.size(), k = nums.size()-1; long long res = 0; for(int i=n-1;i>=0;i--){ res= (res + (v[i].first * nums[k--])%mod)%mod; } return res; } };
用區間的差分優化,O(n)時間內處理區間count,最後時間複雜度O(nlogn)。耗時主要在排序上面code
typedef long long LL; class Solution { public: const int mod = (int)1e9+7; int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) { int n = nums.size(); vector<int> count(n+1); for(auto request:requests){ count[request[0]]++; count[request[1]+1]--; } for(int i=1;i<n;i++) count[i]+=count[i-1]; sort(nums.begin(),nums.end()); sort(count.begin(),count.begin()+n); LL res = 0; for(int i=n-1;i>=0;i--){ res = (res+ 1LL*nums[i]*count[i])%mod; } return res; } };