Count Subarrays With Score Less Than K LeetCode solution in C++
1class Solution {2public:3typedef long long ll;4long long countSubarrays(vector<int> &nums, long long k) {5int n = nums.size();6vector<ll> v(n + 1, 0);7for (int i = 1; i <= n; i++) {8v[i] += v[i - 1] + nums[i - 1];9// doing prefix sum.10}11ll ans = 0;12for (int i = 1; i <= n; i++) {13int low = i;14int high = n;15int ans1 = -1;16// counting the number of sub arrays in which the current element is17// included by doing binary search. The current element is the starting18// element of the subarrays we count.19while (low <= high) {20int mid = low + (high - low) / 2;21ll sum = v[mid] - v[i - 1];22sum *= (mid - i + 1);23if (sum >= k) {24high = mid - 1;25} else {26ans1 = mid;27low = mid + 1;28}29}30if (ans1 != -1) {31ans += (ans1 - i + 1);32}33}34return ans;35}36};