fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. long getMaximumGrossValue(vector<int> arr) {
  5. int n = arr.size();
  6.  
  7. vector<long long> pref(n + 1, 0);
  8.  
  9. for (int i = 1; i <= n; i++)
  10. pref[i] = pref[i - 1] + arr[i - 1];
  11.  
  12. vector<long long> bestPrefix(n + 1);
  13. bestPrefix[0] = pref[0];
  14. for (int i = 1; i <= n; i++)
  15. bestPrefix[i] = max(bestPrefix[i - 1], pref[i]);
  16.  
  17. vector<long long> bestSuffix(n + 1);
  18. bestSuffix[n] = pref[n];
  19. for (int i = n - 1; i >= 0; i--)
  20. bestSuffix[i] = max(bestSuffix[i + 1], pref[i]);
  21.  
  22. long long ans = LLONG_MIN;
  23.  
  24. for (int b = 0; b <= n; b++) {
  25. long long cur = 2LL * bestPrefix[b]
  26. - 2LL * pref[b]
  27. + 2LL * bestSuffix[b]
  28. - pref[n];
  29. ans = max(ans, cur);
  30. }
  31.  
  32. return ans;
  33. }
  34.  
  35. int main() {
  36. // Example from the problem description
  37. std::vector<int> arr = {-5, 3, 9, 4};
  38. // vector<int> arr = {-1,1,-2,-2};
  39. // vector<int> arr= {4,-8,2,-10,3,-20};
  40. std::cout << "Max Gross Value: " << getMaximumGrossValue(arr) << std::endl; // Output: 21
  41. return 0;
  42. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Max Gross Value: 21