Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Find the Best Sightseeing Pair
Next article icon

Find the Best Sightseeing Pair

Last Updated : 31 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer array arr[] where arr[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them. The score of a pair (i < j) of sightseeing spots is arr[i] + arr[j] + i - j: the sum of arr[]of the sightseeing spots, minus the distance between them. Find the maximum score of a pair of sightseeing spots.

Examples:

Input: arr[]= {8, 1, 5, 2, 6}
Output: 11
Explanation: For i = 0, j = 2, arr[i] + arr[j] + i - j = 8 + 5 + 0 - 2 = 11

Input: arr= [1, 2]
Output: 2
Explanation: For i = 0, j = 1, arr[i] + arr[j] + i - j = 2 + 1 + 0 - 1 = 2

Approach: To solve the problem, follow the below idea:

Since our task is to find max{ (arr[i]+i) + (arr[j]-j) } for all i<j.

So we can say that we want maximum of arr[i]+i and maximum of arr[j]-j.

  • Subproblem: find max (arr[i]-i) after i.
  • Recurrence Relation: max_after(i) = max{ arr[i]-i, max_after(i+1) }.
  • Finally ans would be maximum of arr[i]+i+max_after(i+1).

Step-by-step algorithm:

  • Maintain an array max_after[], such that max_after[i] stores the maximum value of arr[j] - j among all j >= i.
  • Now, iterate from 0 to N - 1, and for every index i store the maximum value of arr[i] + i + max_after[i] and store it in ans.
  • Return ans as the final answer.

Below is the implementation of the above algorithm:

C++
#include <bits/stdc++.h> using namespace std;  int maxScoreSightseeingPair(vector<int>& arr) {     // This function finds the best sightseeing pair in a     // city represented by an array values.     //  - max_after: stores the maximum sightseeing score     //  obtainable starting from city i+1      int N = arr.size();     vector<int> max_after(N, 0);      // Initialize max_after for the last city (no city after     // it).     max_after[N - 1] = arr[N - 1] - (N - 1);      // Fill max_after array in reverse order.     for (int i = N - 2; i >= 0; i--) {         max_after[i] = max(max_after[i + 1], arr[i] - i);     }      int ans = 0;     // Iterate through all cities except the last one.     for (int i = 0; i < N - 1; i++) {         // Calculate the total sightseeing score for the         // current city and its best pairing city (i+1).         ans = max(ans, arr[i] + i + max_after[i + 1]);     }      return ans; }  int main() {     // Driver code to test the function     vector<int> arr = { 8, 1, 5, 2, 6 };      int maxScore = maxScoreSightseeingPair(arr);     cout << "Max sightseeing score: " << maxScore << endl;     return 0; } 
Java
import java.util.Arrays;  public class MaxScoreSightseeingPair {     public static int maxScoreSightseeingPair(int[] arr)     {         // This function finds the best sightseeing pair in         // a city represented by an array values.         //  - maxAfter: stores the maximum sightseeing score         //  obtainable starting from city i+1          int N = arr.length;         int[] maxAfter = new int[N];          // Initialize maxAfter for the last city (no city         // after it).         maxAfter[N - 1] = arr[N - 1] - (N - 1);          // Fill maxAfter array in reverse order.         for (int i = N - 2; i >= 0; i--) {             maxAfter[i]                 = Math.max(maxAfter[i + 1], arr[i] - i);         }          int ans = 0;         // Iterate through all cities except the last one.         for (int i = 0; i < N - 1; i++) {             // Calculate the total sightseeing score for the             // current city and its best pairing city (i+1).             ans = Math.max(ans,                            arr[i] + i + maxAfter[i + 1]);         }          return ans;     }      public static void main(String[] args)     {         // Driver code to test the function         int[] arr = { 8, 1, 5, 2, 6 };          int maxScore = maxScoreSightseeingPair(arr);         System.out.println("Max sightseeing score: "                            + maxScore);     } }  // This code is contributed by Shivam 
Python
def max_score_sightseeing_pair(arr):     N = len(arr)     max_after = [0] * N      max_after[N - 1] = arr[N - 1] - (N - 1)      for i in range(N - 2, -1, -1):         max_after[i] = max(max_after[i + 1], arr[i] - i)      ans = 0     for i in range(N - 1):         ans = max(ans, arr[i] + i + max_after[i + 1])      return ans   # Driver code to test the function arr = [8, 1, 5, 2, 6] max_score = max_score_sightseeing_pair(arr) print("Max sightseeing score:", max_score) 
JavaScript
// Function to calculate the maximum score for a sightseeing pair function maxScoreSightseeingPair(arr) {     // Get the length of the array     const N = arr.length;     // Initialize an array to store the maximum values after each index     const maxAfter = new Array(N).fill(0);      // Calculate the maximum value after each index     maxAfter[N - 1] = arr[N - 1] - (N - 1);     for (let i = N - 2; i >= 0; i--) {         maxAfter[i] = Math.max(maxAfter[i + 1], arr[i] - i);     }      // Initialize a variable to store the maximum score     let ans = 0;     // Iterate through the array to find the maximum score     for (let i = 0; i < N - 1; i++) {         ans = Math.max(ans, arr[i] + i + maxAfter[i + 1]);     }      // Return the maximum score     return ans; }  // Driver code to test the function const arr = [8, 1, 5, 2, 6]; const maxScore = maxScoreSightseeingPair(arr); console.log("Max sightseeing score:", maxScore);  // This code is contributed by Shivam Gupta 

Output
Max sightseeing score: 11 

Time complexity: O(N), where N is the size of input subarray arr[].
Auxiliary Space: O(N)


Next Article
Find the Best Sightseeing Pair

V

vforvikram
Improve
Article Tags :
  • Dynamic Programming
  • DSA
  • Arrays
  • Google
Practice Tags :
  • Google
  • Arrays
  • Dynamic Programming

Similar Reads

    Best meeting point in 2D binary array
    You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in a group. And the group of two or more people wants to meet and minimize the total travel distance. They can meet anywhere means that there might be a home or not. The distance is calculated using Manhattan Distance,
    8 min read
    Find the minimum cost to cross the River
    Given an integer N which is the number of villagers who need to cross a river but there is only one boat on which a maximum of 2 person can travel. Each person i has to pay some specific price Pi to travel alone in the boat. If two person i, j travel in the boat then they have to pay max(Pi, Pj). Th
    7 min read
    Find the number of unique pairs satisfying given conditions
    Given an array arr[] of distinct positive elements, the task is to find the number of unique pairs (a, b) such that a is the maximum and b is the second maximum element of some subarray of the given array.Examples: Input: arr[] = {1, 2, 3} Output: 2 {1, 2}, {2, 3}, {1, 2, 3} are the subarrays and th
    7 min read
    Find all Pairs possible from the given Array
    Given an array arr[] of N integers, the task is to find all the pairs possible from the given array. Note: (arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs.Examples: Input: arr[] = {1, 2} Output: (1, 1), (1, 2), (2, 1), (
    4 min read
    Sudo Placement | Beautiful Pairs
    Given two arrays of integers where maximum size of first array is big and that of second array is small. Your task is to find if there is a pair in the first array whose sum is present in the second array. Examples: Input: 4 1 5 10 8 3 2 20 13 Output: 1 Approach: We have x + y = z. This can be rewri
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences