FastPrepMaximum Non-Decreasing Array Length

Maximum Non-Decreasing Array Length

Visa logoVisa● HardFULLTIMENEW GRADOA
Learn

Problem statement

You are given an array arr of positive integers. In one operation, choose two adjacent elements and replace them with their sum.

Perform zero or more operations so that the resulting array is non-decreasing: every element is greater than or equal to the element before it. Return the maximum possible length of the resulting array.

Function

optimalSumOperations(arr: int[]) → int

Examples

Example 1

arr = [2,4,1,6,12]return = 4

Merge 1 and 6 to obtain [2, 4, 7, 12]. This array is non-decreasing and has the maximum possible length of 4.

Example 2

arr = [5,4,3,2]return = 2

Keep 5 as the first segment and merge the remaining values into 9, producing [5, 9].

Constraints

  • 1 <= arr.length <= 2 * 10^3.
  • 1 <= arr[i] <= 10^9.

Source note: The gallery contains two independent HackerRank captures of the adjacent-sum non-decreasing array task; the newer image preserves the visible function signature, example, and constraints.

More Visa problems

See Visa hiring insights
public int optimalSumOperations(int[] arr) {
  // write your code here
}
arr[2,4,1,6,12]
expected4
Checking account…