FastPrepMaximum Sum of Balanced Subsequence

Maximum Sum of Balanced Subsequence

ServiceNow logoServiceNow● MediumOA
Learn

Problem statement

You are given a 0-indexed integer array nums.

A non-empty subsequence chosen from indices i[0] < i[1] < ... < i[k - 1] is balanced when every adjacent pair of chosen indices satisfies nums[i[j]] - nums[i[j - 1]] = i[j] - i[j - 1]. A subsequence of length one is balanced.

Return the maximum possible sum of a balanced subsequence.

A subsequence is formed by deleting zero or more elements without changing the relative order of the remaining elements.

Function

maxSumOfBalancedSubsequence(nums: int[]) → int

Examples

Example 1

nums = [1, 2, 3]return = 6

For every index i, nums[i] - i = 1. Therefore all three values form a balanced subsequence with sum 1 + 2 + 3 = 6.

Example 2

nums = [3, 2, 1]return = 3

The transformed values nums[i] - i are 3, 1, and -1. No two indices can belong to the same balanced subsequence, so the best choice is the single value 3.

Constraints

  • 1 <= nums.length <= 100000
  • -10000 <= nums[i] <= 10000

More ServiceNow problems

See ServiceNow hiring insights
public int maxSumOfBalancedSubsequence(int[] nums) {
    // write your code here
}
nums[1, 2, 3]
expected6
Checking account…