employer cover photo
employer logo
employer logo

Palantir Technologies

Is this your company?

Palantir Technologies Interview Question

Max sum subsequence of an array

Interview Answers

Anonymous

Apr 16, 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

Anonymous

Jul 22, 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.

Anonymous

Feb 15, 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

Anonymous

Feb 9, 2015

see Wikipedia...