FastPrepLargest Later-Minus-Earlier Difference
Problems/Largest Later-Minus-Earlier Difference

Largest Later-Minus-Earlier Difference

Indeed logoIndeed● EasyNEW GRADOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: In an Indeed Prime platform test, which the report says is not Indeed's own hiring test, the second of four questions asks for the biggest gap you can get by subtracting an earlier array value from a later one. The report gives it in one line with no example.

The report does not say what to return when no later number is bigger than an earlier one. Here you return the largest difference anyway, so the answer can be 0 or negative. The array has 2 to 5 * 10^4 numbers from -10^6 to 10^6, which are practice choices.

The judged task matches the report at about 80%.

You are given an integer array nums. Pick two indices i < j and compute nums[j] - nums[i]: a later number minus an earlier one.

Return the largest value of nums[j] - nums[i] over all such pairs. The answer can be 0 or negative, for example when the numbers never go up.

Function

maxDifference(nums: int[]) → int

Examples

Example 1

nums = [4,9,1,7,3]return = 6

Taking 4 then 9 gives 9 - 4 = 5. Taking 1 (index 2) then 7 (index 3) gives 7 - 1 = 6, which is the largest. The 9 and the 1 do not give 8, because the 1 comes after the 9. The answer is 6.

Example 2

nums = [8,5,3,2]return = -1

The numbers only go down, so every later-minus-earlier difference is negative. The closest pair is 3 then 2, which gives 2 - 3 = -1. The answer is -1.

Example 3

nums = [6,6]return = 0

The only pair gives 6 - 6 = 0. The answer is 0.

Constraints

  • 2 <= nums.length <= 5 * 10^4
  • -10^6 <= nums[i] <= 10^6

More Indeed problems

  • Insert into an Unrolled Linked ListPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
  • Course Completion OrderPHONE SCREEN · Seen May 2025
  • Recipes You Can PreparePHONE SCREEN · Seen May 2025
All Indeed interview questionsSee Indeed hiring insights
Saved
class Solution {
    public int maxDifference(int[] nums) {
        // Write your code here.
    }
}
Checking account…