Binary Search
class Solution {
public:
void sol(vector<int>& nums, int s, int e, int& res, int& index) {
if(s >= e) {
if(res < nums[s]) {
res = nums[s];
index = s;
}
return;
}
int mid = s +(e-s)/2;
sol(nums, s, mid, res, index);
sol(nums, mid+1, e, res, index);
}
int findPeakElement(vector<int>& nums) {
int res = INT_MIN;
int i = 0;
sol(nums, 0, nums.size()-1, res, i);
return i;
}
};
TLE - 102 / 106
class Solution {
public:
bool checkVowels(char ch) {
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
int maxVowels(string s, int k) {
int count = 0;
int res = 0;
for(int i = 0; i <= s.size()-k; i++) {
count = 0;
int j = i;
while(j < i+k ){
if(checkVowels(s[j])) count++;
j++;
}
res = max(res, count);
}
return res;
}
};
Memory Limit Exceed - 80/106 (TC Optimized Sol.)
class Solution {
public:
bool checkVowels(char ch) {
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
void sol(string str, int s, int e, int& count) {
if(s >= e) {
if(checkVowels(str[s])) {
count++;
}
return;
}
int mid = s +(e-s)/2;
sol(str, s, mid, count);
sol(str, mid+1, e, count);
}
int maxVowels(string s, int k) {
int count = 0;
int res = 0;
for(int i = 0; i <= s.size()-k; i++) {
count = 0;
sol(s, i, i+k-1, count);
res = max(res, count);
}
return res;
}
};
Last updated
Was this helpful?