Leetcode Problem:
Summary
- This solution is used to find the power of all subarrays of size k in a given array of integers
- The power of a subarray is defined as its maximum element if all its elements are consecutive and sorted in ascending order, otherwise -1.
Approach
- This solution uses a sliding window approach with two nested loops to check for consecutive elements
- It keeps track of the current window's start index, end index, and the count of consecutive elements
- If the count of consecutive elements equals k, the maximum element in the current window is added to the result array
- Otherwise, -1 is added.
Complexity
- O(n*k) where n is the size of the input array, k is the size of the subarray
Solution Code:
class Solution {
public:
vector resultsArray(vector& nums, int k) {
vector ans;
int acd_cnt = 1;
int cmp_num = nums[0];
for(int i = 1 ; i < k ;i++){
if(cmp_num + 1 == nums[i]){
acd_cnt++;
} else {
acd_cnt = 1;
}
cmp_num = nums[i];
}
if(acd_cnt == k){
ans.push_back(cmp_num);
} else {
ans.push_back(-1);
}
for(int i = k ; i < nums.size(); i++){
if(cmp_num + 1 == nums[i]){
acd_cnt++;
} else {
acd_cnt = 1;
}
if(acd_cnt >= k){
ans.push_back(nums[i]);
} else {
ans.push_back(-1);
}
cmp_num = nums[i];
}
return ans;
}
};
'알고리즘' 카테고리의 다른 글
Defuse the Bomb (0) | 2025.02.22 |
---|---|
Shortest Subarray with Sum at Least K (0) | 2025.02.22 |
Find Elements in a Contaminated Binary Tree (0) | 2025.02.21 |
Shortest Subarray to be Removed to Make Array Sorted (0) | 2025.02.21 |
Minimized Maximum of Products Distributed to Any Store (0) | 2025.02.21 |