Question:
Given an array A[1..N], find the i, j such that for all 1 <= i < j <= N, find the largest A[j] - A[i]
Answer:
For array A[1..N]
let f(n) to be the result value for the first n elements.
let m(n) to be the smallest element of A[1]..A[n].
f(n) = max{ f(n-1), A[n] - m(n-1) }
m(n) = min{ m(n-1), A[n] }
Solve with DP, O(n) time, O(1) space.
Friday, February 29, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment