← 返回 akunacapital 的题目列表Array Challenge: Left-Comparison Running Counter
类型:qbank
For each i, start a counter at 0 and compare a[i] against every left element a[j] (j<i): add |a[i]-a[j]| if a[j]<a[i], subtract it if a[j]>a[i]. Return the array of counters. The signs cancel so result[i] = i*a[i] - prefix_sum(0..i-1), giving an O(n) solution.
Requirements
For each i-th element of an array:
Initialize a counter to 0.
Compare a[i] with every element to its left (a[i-1], a[i-2], ..., a[0]). If the left element is greater, subtract the absolute difference from the counter; if it is smaller, add the absolute difference.
Return a new array of the final counter values.
Examples
n = 3
arr = [2, 4, 3]
arr[0] = 2: no elements to the left, counter = 0.
arr[1] = 4: compare with 2 (smaller), add |4 - 2| = 2, counter = 2.
arr[2] = 3: compare with 4 (greater), 0 - |3 - 4| = -1; then with 2 (smaller), -1 + |3 - 2| = 0.
Answer: [0, 2, 0].
Notes
The sign rule makes the absolute values cancel: for index i, every left element smaller than a[i] contributes +(a[i]-a[j]) and every larger one contributes -(a[j]-a[i]) = +(a[i]-a[j]). So each term is just a[i] - a[j] regardless of order, and
result[i] = i * a[i] - (a[0] + a[1] + ... + a[i-1])
Maintain a running prefix sum and compute each entry in O(1). The nested O(n^2) loop produces correct values but hits runtime-limit failures on the hidden tests.
Preparation
Derive the i*a[i] - prefixSum identity by hand, then implement the single O(n) pass.
Confirm it matches the brute-force result on small random arrays before trusting it under the timer.