Maximize Value - C++ Solution

1. Introduction

In this blog post, we explore an interesting array processing problem: maximizing the value of the expression A[s] - A[r] + A[q] - A[p], given specific conditions on the indices p, q, r, and s. This problem demonstrates an application of dynamic programming and array manipulation.

Problem

Given an array A, the task is to maximize the value of the expression A[s] - A[r] + A[q] - A[p], where p, q, r, and s are indices of the array satisfying s > r > q > p.

Example:

Input: [3, 9, 10, 1, 30, 40]

Output: 46

Explanation: The expression (40 - 1 + 10 - 3) results in the maximum value of 46.

2. Solution Steps

1. Precompute the maximum and minimum values for different parts of the expression.

2. Iterate through the array and compute the maximum value of the expression at each step.

3. Return the maximum value obtained.

3. Code Program

#include <iostream>
#include <vector>
#include <climits>
using namespace std;

int maximizeValue(vector<int>& A) {
    int n = A.size();
    if (n < 4) return 0;

    vector<int> maxS(n, INT_MIN);
    vector<int> maxSR(n, INT_MIN);
    vector<int> maxSRQ(n, INT_MIN);

    // Precompute maximum of A[s]
    for (int s = n - 1; s >= 3; s--) {
        maxS[s] = max(maxS[s + 1], A[s]);
    }

    // Precompute maximum of A[s] - A[r]
    for (int r = n - 2; r >= 2; r--) {
        maxSR[r] = max(maxSR[r + 1], maxS[r + 1] - A[r]);
    }

    // Precompute maximum of A[s] - A[r] + A[q]
    for (int q = n - 3; q >= 1; q--) {
        maxSRQ[q] = max(maxSRQ[q + 1], maxSR[q + 1] + A[q]);
    }

    // Compute the maximum value of the expression
    int maxValue = INT_MIN;
    for (int p = 0; p < n - 3; p++) {
        maxValue = max(maxValue, maxSRQ[p + 1] - A[p]);
    }

    return maxValue;
}

int main() {
    vector<int> A = {3, 9, 10, 1, 30, 40};
    cout << "Maximum value of expression: " << maximizeValue(A) << endl;
    return 0;
}

Output:

Maximum value of expression: 46

Explanation:

The maximizeValue function uses dynamic programming to maximize the expression value. It precomputes the maximum values for the segments A[s], A[s] - A[r], and A[s] - A[r] + A[q] in the array. Starting from the end of the array, it calculates these maximums iteratively. Then, it iterates over the array to find the maximum value of A[s] - A[r] + A[q] - A[p] for each p. The final result is the maximum value of this expression that can be obtained from the array, which is 46 for the given example.


Comments