newb_ie

min_max sum of subarray size k

Jul 8th, 2020
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1.  /*
  2.     \_\
  3.    (_**)
  4.   __) #_
  5.  ( )...() => HI
  6.  || | |I|
  7.  || | |()__/
  8.  /\(___)
  9.  */
  10. #include<bits/stdc++.h>
  11. using namespace std;
  12. using lli = int64_t;
  13. void min_max_sum(int n,vector<int> nums,int k){
  14.     int l = 0,r = 0;
  15.     int min_sum = INT_MAX,max_sum = INT_MIN,sum = 0;
  16.     while(r < n){
  17.         while(r - l < k and r < n){
  18.             sum += nums[r++];
  19.         }
  20.         min_sum = min(min_sum,sum);
  21.         max_sum = max(max_sum,sum);
  22.         if(r - l == k){
  23.             sum -= nums[l++];
  24.         }
  25.     }
  26.     cout << min_sum << " " << max_sum << "\n";
  27. }
  28. int main(){
  29.     ios::sync_with_stdio(false);
  30.     cin.tie(nullptr);
  31.     int n,k;
  32.     cin >> n >> k;
  33.     vector<int> nums(n);
  34.     for(int i = 0;i < n; i++){
  35.         cin >> nums[i];
  36.     }
  37.     //generate min max sum of subarray length k (distinct array);
  38.     min_max_sum(n,nums,k);
  39. }
Add Comment
Please, Sign In to add comment