Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k.
Example:
Input: arr[]={10,5,2,7,8,7}, k=3
Output: 10 7 8 8
Approach
C++
#include <bits/stdc++.h>using namespace std;//functiom to get the maximum value in the windowint getmax(stack<pair<int, int>> &st1, stack<pair<int, int>> &st2){//if any stack is empty then return the top//elmemt of one which is non emptyif (st1.empty() || st2.empty())return st1.empty() ? st2.top().second : st1.top().second;//else return the maximum of both the stacksreturn max(st1.top().second, st2.top().second);}//function to add new elementvoid add(stack<pair<int, int>> &st1, int new_element){//find the new maximum value if//stack is empty then maximum is the current element//else the maximum is max of cuurent element and top of stackint max1 = st1.empty() ? new_element :max(new_element, st1.top().second);//push into the stack with new maxst1.push({new_element, max1});}//function to remove the elementvoid remove(stack<pair<int, int>> &st1,stack<pair<int, int>> &st2){//if stack 2 is emptyif (st2.empty()){//put all of stack one into stack 2//means convert into the queuewhile (!st1.empty()){int element = st1.top().first;st1.pop();int max1 = st2.empty() ? element :max(element, st2.top().second);st2.push({element, max1});}}//delete the top element from stack 2st2.pop();}//function to find the maximum in window of//given sizevector<int> maxSlidingWindow(vector<int> &nums, int k){stack<pair<int, int>> st1, st2;//add k elementsfor (int i = 0; i < k; i++)add(st1, nums[i]);vector<int> res;//push into the anwerres.push_back(getmax(st1, st2));//inerate for remaining elementsfor (int i = k; i < nums.size(); i++){//remove the start elementremove(st1, st2);//add new elementsadd(st1, nums[i]);//push into the resultres.push_back(getmax(st1, st2));}return res;}int main(){vector<int> arr = {10, 5, 2, 7, 8, 7};int k = 3;vector<int> maximum = maxSlidingWindow(arr, k);for (int i = 0; i < maximum.size(); i++)cout << maximum[i] << " ";return 0;}
No comments:
Post a Comment