File tree Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+
3+ Author : Manas Rawat
4+ Date : 27/03/2024
5+ Problem : Subarray Product Less Than K
6+ Difficulty : Medium
7+ Problem Link : https://leetcode.com/problems/subarray-product-less-than-k/description/?envType=daily-question&envId=2024-03-27
8+ Video Solution : NA
9+
10+ */
11+
12+
13+ class Solution {
14+ public:
15+ int numSubarrayProductLessThanK (vector<int >& nums, int k) {
16+ if (k == 0 ) return 0 ;
17+ double logK = log (k);
18+ int m = nums.size () + 1 ;
19+ vector<double > logsPrefixSum (m);
20+
21+ for (int i = 0 ; i < nums.size (); i++) {
22+ logsPrefixSum[i + 1 ] = logsPrefixSum[i] + log (nums[i]);
23+ }
24+
25+ int totalCount = 0 ;
26+
27+ for (int currIdx = 0 ; currIdx < m; currIdx++) {
28+ int low = currIdx + 1 , high = m;
29+ while (low < high) {
30+ int mid = low + (high - low) / 2 ;
31+ if (logsPrefixSum[mid] < logsPrefixSum[currIdx] + logK - 1e-9 ) {
32+ low = mid + 1 ;
33+ } else {
34+ high = mid;
35+ }
36+ }
37+ totalCount += low - currIdx - 1 ;
38+ }
39+
40+ return totalCount;
41+ }
42+ };
43+
Original file line number Diff line number Diff line change 1+ /*
2+
3+ Author : Manas Rawat
4+ Date : 28/03/2024
5+ Problem : Length of Longest Subarray With at Most K Frequency
6+ Difficulty : Medium
7+ Problem Link : https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/description/
8+ Video Solution : NA
9+
10+ */
11+
12+
13+ class Solution {
14+ public:
15+ int maxSubarrayLength (vector<int >& nums, int k) {
16+ int ans = 0 ;
17+ int l = 0 , r = 0 ;
18+ map<int , int > f;
19+
20+ while (r < nums.size ()) {
21+ ++f[nums[r]];
22+
23+ while (f[nums[r]] > k){
24+ --f[nums[l]];
25+ if (f[nums[l]] == 0 )
26+ f.erase (nums[l]);
27+
28+ ++l;
29+ }
30+
31+ ans = max (r - l + 1 , ans);
32+ ++r;
33+ }
34+
35+ return ans;
36+ }
37+ };
You can’t perform that action at this time.
0 commit comments