dsa-practice/libs/chapter1/sliding_window.cpp

83 lines
1.9 KiB
C++

#include "chapter1.hpp"
/**
* \brief sliding_window_max_sum
*
* Detailed description
*
* \param array The input array
* \param len The length of the input array
* \param k_len The length of the subarray
* \return return int The maximum found in the subarray
*/
int sliding_window_max_sum(int* array, int len, int k_len){
int current_max = 0;
int* window_beg = array;
int* window_end = (array + k_len);
int previous_beg = 0;
// initial sum
for (int i = 0; i < k_len; i++){
current_max += array[i];
}
previous_beg = *window_beg;
window_beg += 1;
window_end += 1;
// iterate window
int current_sum = current_max;
while(window_end != (array + len - 1)){
current_sum = current_sum - previous_beg + *window_end;
if (current_sum > current_max){
current_max = current_sum;
}
previous_beg = *window_beg;
window_beg += 1;
window_end += 1;
}
return current_max;
}
/**
* \brief sliding_window_shortest_subarray
*
* Find the shortest subarray that is greater than or equal to x.
*
* \param array The intput array
* \param len The length of the input array
* \param x The threshold to compare to
* \return return the length of the shortest subarray
*/
int sliding_window_shortest_subarray(int* array,int len, int x){
int* window_beg = &array[0];
int* window_end = &array[1];
int current_sum = array[0] + array[1];
int min_len = len;
int sub_array_len = len;
while(window_beg != (array + len - 1)){
if(current_sum < x){
window_end += 1;
current_sum += *window_end;
}
if (current_sum >= x){
sub_array_len = window_end - window_beg + 1;
if(sub_array_len < min_len){
min_len = sub_array_len;
}
current_sum -= *window_beg;
window_beg += 1;
if(window_beg > window_end){
window_end += 1;
current_sum += *window_end;
}
}
}
return min_len;
}