- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Best Sightseeing Pair in C++
Suppose we have an array A of positive integers, now A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i. Now the score of a pair (i < j) of sightseeing spots is follows this formula (A[i] + A[j] + i - j): We have to find the maximum score of a pair of sightseeing spots. So if the input is like [8,1,5,2,6], then the output will be 11, as i = 0, j = 2, the value of A[0] + A[2] + 0 – 2 = 8 + 5 + 0 – 2 = 11.
To solve this, we will follow these steps −
Set ret := 0, maxVal := 0, set n := size of A
for i in range 0 to n – 1
ret := max of ret and (maxVal + A[i] – i)
maxVal := max of (A[i] + i) and maxVal
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int maxScoreSightseeingPair(vector<int>& A) { int ret = 0; int maxVal = 0; int n = A.size(); for(int i = 0; i < n; i++){ ret = max(ret, maxVal + A[i] - i); maxVal = max(A[i] + i, maxVal); } return ret; } }; main(){ vector<int> v1 = {8, 1, 5, 2, 6}; Solution ob; cout << (ob.maxScoreSightseeingPair(v1)); }
Input
[8,1,5,2,6]
Output
11
Advertisements
To Continue Learning Please Login
Login with Google