看到题目后感觉可以用动态规划,但是找不到状态转移方程,用本办法写了个算法,最终超时
class Solution { public: int maxScoreSightseeingPair(vector<int>& A) { if (A.empty()) { return 0; } double max_value = 0; size_t max_i = 0; size_t max_j = 0; vector<vector<int>> map_val(A.size(), vector<int>(A.size(), 0)); for (size_t i = 0; i < A.size(); i++) { for (size_t j=i + 1; j < A.size(); j++) { map_val[i][j] = A[i] + A[j] + i -j; if (map_val[i][j] > max_value) { max_value = map_val[i][j]; max_i = i; max_j = j; } } } return max_value; } };
在看了答案之后恍然大悟,原来每一个value的值可以看作是值加上它的序号,第i个值与其之前的最大值之间的和就是前i个数组对应的题目解,状态转移方程就建立起来了,代码如下:
class Solution { public: int maxScoreSightseeingPair(vector<int>& A) { if (A.size() < 2) { return 0; } map<int, int> value_map; int result = 0; value_map[0] = A[0]; int max_value = A[0]; for (size_t i = 1; i < A.size(); i++) { int value_i = i + A[i]; if (max_value < value_i) { max_value = value_i; } value_map[i] = max_value; if (result < value_map[i-1] + A[i] - i) { result = value_map[i-1] + A[i] - i; } } return result; } };