th0m45s5helby

Untitled

Sep 14th, 2021
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include <iostream>
  2. #include <climits>
  3. using namespace std;
  4.  
  5. void printArray(int arr[], int n)
  6. {
  7.     for (int i = 0; i < n; i++) {
  8.         cout << arr[i] << " ";
  9.     }
  10.     cout << endl;
  11. }
  12.  
  13. int maximizeExpression(int A[], int n)
  14. {
  15.     int first[n + 1], second[n], third[n - 1], fourth[n - 2];
  16.  
  17.     for (int i = 0; i <= n - 3; i++) {
  18.         first[i] = second[i] = third[i] = fourth[i] = INT_MIN;
  19.     }
  20.  
  21.     first[n - 2] = second[n - 2] = third[n - 2] = INT_MIN;
  22.     first[n - 1] = second[n - 1] = first[n] = INT_MIN;
  23.  
  24.     for (int i = n - 1; i >= 0; i--) {
  25.         first[i] = max(first[i + 1], A[i]);
  26.     }
  27.  
  28.     for (int i = n - 2; i >= 0; i--) {
  29.         second[i] = max(second[i + 1], first[i + 1] - A[i]);
  30.     }
  31.  
  32.     for (int i = n - 3; i >= 0; i--) {
  33.         third[i] = max(third[i + 1], second[i + 1] + A[i]);
  34.     }
  35.  
  36.     for (int i = n - 4; i >= 0; i--) {
  37.         fourth[i] = max(fourth[i + 1], third[i + 1] - A[i]);
  38.     }
  39.  
  40.     return fourth[0];
  41. }
  42.  
  43. int main()
  44.  
  45. {
  46.     int n;
  47.     cin>>n;
  48.    
  49.     int arr[n];
  50.     for(int i=0;i<n;i++){
  51.         cin>>arr[i];
  52.     }
  53.      if (n >= 4) {
  54.         cout << maximizeExpression(arr, n);
  55.     }
  56.  
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment