Problem · Array

Get the Fewest Moves (~Operations~)~

MediumAmazonNEW GRADFULLTIMEOA
See Amazon hiring insights

Similar to LC 2772

You are given an integer list named data. The objective is to adjust all elements in this list so that each becomes zero. You can carry out the following move any number of times:

  • Pick a prefix portion of the list and either increase or decrease every element in that prefix by 1.
  • Your task is to figure out the fewest moves required to turn all the elements into zero.

    A prefix is a contiguous group of items that includes the first element in the cart. for example [1], [1,2], [1,2,3] are prefixes of [1,2,3,4,5].

    The function you implement should print a single number — the minimum number of steps needed.

    A prefix segment refers to a continuous collection of elements starting from the first item in the sequence. For instance, [1], [1, 2], [1, 2, 3], and so on are valid prefixes of the sequence [1, 2, 3, 4, 5].

    It is assured that turning all values in the list to zero is always achievable.

    Note: This problem has been intentionally rephrased due to unavoidable circumstances. The rephrased version preserves the exact meaning of the original prompt. You can view the original wording in the Problem Source section. Thank you for understanding! 🐹 (06-23-2026 :)

    Examples
    01 · Example 1
    data = [3, 2, 0, 0, -1]
    return = 5

    For n = 5 and cart = [3, 2, 0, 0, -1], one optimal set of operations is:

    • Operation 1: Let the prefix length be 1, and decrement by 1. cart after this operation is [2, 2, 0, 0, -1].
    • Operation 2: Let the prefix length be 2, and decrement by 1. cart after this operation is [1, 1, 0, 0, -1].
    • Operation 3: Let the prefix length be 4, and decrement by 1. cart after this operation is [0, 0, -1, -1, -1].
    • Operation 4: Let the prefix length be 2, and decrement by 1. cart after this operation is [-1, -1, -1, -1, -1].
    • Operation 5: Let the prefix length be 5, and increment by 1. cart after this operation is [0, 0, 0, 0, 0].

    The answer is 5.

    02 · Example 2
    data = [3, 2, 1]
    return = 3
    • Operation 1: Let the prefix length be 2, and decrement by 1. cart after this operation is [2, 1, 1].
    • Operation 2: Let the prefix length be 1, and decrement by 1. cart after this operation is [1, 1, 1].
    • Operation 3: Let the prefix length be 3, and decrement by 1. cart after this operation is [0, 0, 0].
    Constraints
  • 1 ≤ n ≤ 10^5
  • -10^9 ≤ data[i] ≤ 10^9
  • More Amazon problems
    drafts saved locally
    public int minOperations(int[] data) {
      // write your code here
    }
    
    data[3, 2, 0, 0, -1]
    expected5
    sign in to submit