[Implementation idea]: [Native way] A native way is to check all triple candidates, filter out illegals and find the one the maximum sum. Complexity is O(n^3). [Better way] Apply dynamic programming. Complexity is O(nlogn) Complexity is O(n) Input: [1,2,1,2,6,7,5,1], 2 Output: [0, 3, 5] Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5]. We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger. Assume A(i, j) represents the maximum j Non-Overlapping Sub-arrays sum whose last chosen index is at position i. A(i, 1) = 1. sum(A(k)) k = i, i-1, ... i-k+1, if i >= (k - 1). 2. 0, otherwise. A(i, 2) = 1. A(i, 1) + max(A(i-k, 1)); if i >= (2*k - 1). 2. 0, otherwise. A(i, 3) = 1. A(i, 1) + max(A(i-k, 2)); if i >= (3*k - 1). 2. 0, otherwise. Formula A(i,1) is intuitive; Formula A(i,2) comes from the fact that - we must ended ...
留言
張貼留言