Approach
Sorting and greedy selection
For Find the Sum of Subsequence Powers, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 53 lines of C++ from the credited upstream file 3098.cpp.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int sumOfPowers(vector<int>& nums, int k) {4 const int n = nums.size();5 ranges::sort(nums);6 vector<vector<vector<vector<int>>>> mem(7 n + 1, vector<vector<vector<int>>>(8 n + 1, vector<vector<int>>(n + 1, vector<int>(k + 1, -1))));9 return sumOfPowers(nums, 0, k, -1, -1, -1, mem);10 }11 12 private:13 static constexpr int kMod = 1'000'000'007;14 15 16 17 18 19 int sumOfPowers(const vector<int>& nums, int i, int k, int lastPickedIndex,20 int firstIndex, int secondIndex,21 vector<vector<vector<vector<int>>>>& mem) {22 if (k == 0)23 return nums[secondIndex] - nums[firstIndex];24 if (i == nums.size())25 return 0;26 const int a = hash(lastPickedIndex);27 const int b = hash(firstIndex);28 const int c = hash(secondIndex);29 if (mem[a][b][c][k] != -1)30 return mem[a][b][c][k];31 int newFirstIndex = firstIndex;32 int newSecondIndex = secondIndex;33 if (firstIndex == -1) {34 newFirstIndex = i;35 } else if (secondIndex == -1) {36 newSecondIndex = i;37 } else if (nums[i] - nums[lastPickedIndex] <38 nums[secondIndex] - nums[firstIndex]) {39 newFirstIndex = lastPickedIndex;40 newSecondIndex = i;41 }42 const int pick =43 sumOfPowers(nums, i + 1, k - 1, i, newFirstIndex, newSecondIndex, mem);44 const int skip = sumOfPowers(nums, i + 1, k, lastPickedIndex, firstIndex,45 secondIndex, mem);46 return mem[a][b][c][k] = (pick + skip) % kMod;47 }48 49 constexpr int hash(int x) {50 return x + 1;51 }52};53