Approach

This seems like there is a greedy approach. I think that we can represent by a range. If index i is constraint to be smaller than 2, its range is [0, 2]. And if its difference to the next point is smaller than 3, the range for next point is [-3, 5], and we can keep propagate to the right side. Later I found that the number would be positive, so actually we don’t need to care about the negative part, just calculate the largest part.

Then I think about how to determine the range for the index between two constraint points. Say i and j are constraint, originally I think we do intersect for all the index between them. Actually, we can walk from i first, and replace the upper bound only when the propagated value is smaller than the bound (in this case propagate further is of no use).

After that we of the same thing to propagate to the left side and we get the answer.

For the index 0, the problem say it is 0, that is its upper bound is 0.

Following is a figure for illustration of the algorithm:

Code

class Solution {
public:
    int findMaxVal(int n, vector<vector<int>>& restrictions, vector<int>& diff) {
        vector<int> ans(n, INT_MAX);
        vector<int> blk; // the index of blocking
        for(const auto& r: restrictions) {
            ans[r[0]] = r[1]; // max value
            blk.push_back(r[0]);
        }
        ans[0] = 0;
        blk.push_back(0);
        // greedy right
        for(const int& b: blk) {
            for(int i = b ; ; ++i) {
                if(i == n-1) break;
                int nextAns = ans[i] + diff[i];
                if(nextAns >= ans[i+1]) break;
                ans[i+1] = nextAns;
            }
        }
        // greedy left
        for(const int& b: blk) {
            for(int i = b ; ; --i) {
                if(i == 0) break;
                int nextAns = ans[i] + diff[i-1];
                if(nextAns >= ans[i-1]) break;
                ans[i-1] = nextAns;
            }
        }
        // for(int i = 0 ; i < n ; ++i) {
        //     cout << ans[i] << ' ';
        // } cout << endl;
        return *max_element(ans.begin(), ans.end());
    }
};