Question d’entretien chez Palantir Technologies

Max sum subsequence of an array

Réponses aux questions d'entretien

Utilisateur anonyme

16 avr. 2015

Iterate through that array and comparing the current sum to the maximum sum. If the sum becomes negative at some point, reset it to zero since the maximum sum of the forthcoming elements cannot be larger if you include the negative partial sum. That way, you can solve the problem in O(n) time. It can be speeded up by restarting a new partial sum only on a positive element (or the up to that point largest negative element, which captures the case that all elements are smaller than zero).

3

Utilisateur anonyme

22 juil. 2017

Most of the answers here are wrong (or perhaps the question is wrong, and a subarray is actually wanted instead). In a subsequence, the array elements do not have to be contiguous, hence simply sum up all the positive numbers in the array.

Utilisateur anonyme

15 févr. 2015

Assuming that array contains positive or negative real numbers. (If numbers are only positive, max sum subsequence is obviously the entire array) O(n log n) divide-and-conquer solution outline: 1. Recursively halve the array into array slices of unit 1. 2. Merge array slices, maintaining the totals and start/end indices of 4 types of subsequences: subsq1. The subsequence that contains the greatest sum within the slice subsq2. The subsequence that contains the greatest sum within the slice and that ends at the rightmost cell of the slice subsq3. The subsequence that contains the greatest sum within the slice and starts at the leftmost cell of the slice subsq4. The entire slice While merging 2 slices together update these slices as follows, 1. max(leftSlice.subsq1, rightSlice.subsq1, leftSlice.subsq2 + rightSlice.subsq3) 2. max(rightSlice.subsq2, leftSlice.subsq2 + rightSlice.subsq4) 3. max(leftSlice.subsq3, rightSlice.subsq3 + leftSlice.subsq4) 4. leftSlice.subsq4 + rightSlice.subsq4 When all the array slices are merged, subsq1 will give you the greatest subsequence. We cannot do better than O(n) because we will have to access each element. We probably cannot do better than O(n log n) because we will have to eventually compare subsequence candidates.

2

Utilisateur anonyme

9 févr. 2015

see Wikipedia...