fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. long getMaxCumulativeObservableSum(vector<int> stockPrice, int k) {
  5. unordered_map<int, int> freq; // To track frequency of elements in the current window
  6. long currentSum = 0, maxSum = -1;
  7. int n = stockPrice.size();
  8. int left = 0;
  9.  
  10. for (int right = 0; right < n; ++right) {
  11. int val = stockPrice[right];
  12. freq[val]++;
  13. currentSum += val;
  14.  
  15. // If window size exceeds k, shrink it from left
  16. if (right - left + 1 > k) {
  17. int leftVal = stockPrice[left++];
  18. freq[leftVal]--;
  19. currentSum -= leftVal;
  20. if (freq[leftVal] == 0) freq.erase(leftVal);
  21. }
  22.  
  23. // Check if window size is k and all elements are distinct
  24. if (right - left + 1 == k && freq.size() == k) {
  25. maxSum = max(maxSum, currentSum);
  26. }
  27. }
  28.  
  29. return maxSum;
  30. }
  31.  
  32. int main() {
  33. // Example usage
  34. vector<int> stockPrice = {1, 2, 7, 7, 4, 3, 6};
  35. int k = 3;
  36. cout << getMaxCumulativeObservableSum(stockPrice, k) << endl; // Output: 14
  37. return 0;
  38. }
Success #stdin #stdout 0.01s 5312KB
stdin
45
stdout
14