- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 64 lines of C++ from the credited upstream file 2040.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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 long long kthSmallestProduct(vector<int>& nums1, vector<int>& nums2,4 long long k) {5 vector<int> A1;6 vector<int> A2;7 vector<int> B1;8 vector<int> B2;9 10 seperate(nums1, A1, A2);11 seperate(nums2, B1, B2);12 13 const long negCount = A1.size() * B2.size() + A2.size() * B1.size();14 int sign = 1;15 16 if (k > negCount) {17 k -= negCount; 18 } else {19 k = negCount - k + 1; 20 sign = -1;21 swap(B1, B2);22 }23 24 long l = 0;25 long r = 1e10;26 27 while (l < r) {28 const long m = (l + r) / 2;29 if (numProductNoGreaterThan(A1, B1, m) +30 numProductNoGreaterThan(A2, B2, m) >=31 k)32 r = m;33 else34 l = m + 1;35 }36 37 return sign * l;38 }39 40 private:41 void seperate(const vector<int>& arr, vector<int>& A1, vector<int>& A2) {42 for (const int a : arr)43 if (a < 0)44 A1.push_back(-a);45 else46 A2.push_back(a);47 ranges::reverse(A1); 48 }49 50 long numProductNoGreaterThan(const vector<int>& A, const vector<int>& B,51 long m) {52 long count = 0;53 int j = B.size() - 1;54 55 56 for (const long a : A) {57 while (j >= 0 && a * B[j] > m)58 --j;59 count += j + 1;60 }61 return count;62 }63};64