- 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
Program to find a pair (i, j) where nums[i] + nums[j] + (i -j) is maximized in Python?
Suppose we have a list of numbers called nums, we have to find a pair (i, j) where i < j, and nums[i] + nums[j] + (i - j) is maximized.
So, if the input is like nums = [6, 6, 2, 2, 2, 8], then the output will be 11, as if we pick the two 6 then its score is 6 + 6 + 0 - 1 = 11.
To solve this, we will follow these steps:
large := nums[0]
maxi := 0
for i in range 1 to size of nums, do
large := large - 1
maxi := maximum of large + nums[i] and maxi
large := maximum of large and nums[i]
return maxi
Let us see the following implementation to get better understanding
Example
class Solution: def solve(self, nums): large = nums[0] maxi = 0 for i in range(1, len(nums)): large -= 1 maxi = max(large + nums[i], maxi) large = max(large, nums[i]) return maxi ob = Solution() nums = [6, 6, 2, 2, 2, 8] print(ob.solve(nums))
Input
[6, 6, 2, 2, 2, 8]
Output
11
Advertisements