Leetcode 2786: Visit Array Positions to Maximize Score

grid47
grid47
Exploring patterns and algorithms
Feb 2, 2024 5 min read

You are given an integer array ’nums’ and a positive integer ‘x’. Starting at index 0, you can move to any position j (where i < j). For each position i that you visit, you get a score of nums[i]. If the parities of nums[i] and nums[j] differ, you lose a score of ‘x’. Your goal is to find the maximum score you can accumulate by visiting positions in the array.
Problem
Approach
Steps
Complexity
Input: You are given an integer array nums and a positive integer x.
Example: Input: nums = [5, 10, 3, 7], x = 4
Constraints:
• 2 <= nums.length <= 10^5
• 1 <= nums[i], x <= 10^6
Output: Return the maximum score you can achieve by visiting positions in the array according to the given rules.
Example: Output: 19
Constraints:
Goal: Maximize the total score by choosing the optimal positions to visit based on the parity conditions.
Steps:
• Initialize the scores for the even and odd cases based on nums[0].
• Iterate through the array, updating the scores based on the parity of nums[i] and the maximum possible score from previous positions.
• Return the maximum score from the even or odd score variable.
Goal: The input array length and the value of x.
Steps:
• nums.length is between 2 and 10^5.
• Each value in nums is between 1 and 10^6.
• x is between 1 and 10^6.
Assumptions:
• The input array nums contains integers and is not empty.
Input: Input: [5, 10, 3, 7], x = 4
Explanation: Starting at index 0, we first gain 5 points. Then moving to index 1, we gain 10 but lose 4 points because the parities of 5 (odd) and 10 (even) differ. Then, moving to index 3, we gain 7 but lose another 4 points because the parities of 10 (even) and 7 (odd) differ. The final score is 5 + 10 + 7 - 4 - 4 = 19.

Input: Input: [2, 4, 6, 8], x = 2
Explanation: All values are even, so no penalties are incurred. The total score is 2 + 4 + 6 + 8 = 20.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus