This question evaluates array-processing and algorithmic optimization skills, testing reasoning about element relationships in sequences; it falls under the Coding & Algorithms domain and emphasizes practical application of linear-time algorithm design rather than purely conceptual proofs.
You are given an integer array output (length n ≥ 1).
Define the gain of choosing indices i < j as output[j] - output[i].
Return the maximum gain over all valid pairs (i, j). If no pair yields a positive gain, return 0.
output
:
vector<int>
output[j] - output[i]
for
i < j
, or
0
if all differences are non-positive.
output = [7, 1, 5, 3, 6, 4]
→
5
(buy at
1
, sell at
6
)
output = [5, 4, 3, 2, 1]
→
0
1 ≤ n ≤ 2e5
-1e9 ≤ output[i] ≤ 1e9
Implement int root_node(vector<int> output) efficiently (time better than O(n²)).