Amazon Interview Question
SDE-3sCountry: United States
Interview Type: In-Person
@ChrisK, your solution is not working for input containing all negatives, e.g. [-1,-2,-3]. Also, there is no need in dp list.
Here is my solution with O(n) time / O(1) memory. I hope it covers all corner cases :)
class Main {
public static void main(String[] args) {
System.out.println(solve(new int[] {0,1,-2,3})); // -> 1+3 = 4
System.out.println(solve(new int[] {8,1,-1,2,2,10})); // -> 8+2+10 = 20
System.out.println(solve(new int[] {10,0,0,0,20})); // -> 10+20 = 30
System.out.println(solve(new int[] {-1,-2,-3})); // -> all negatives -> 0
}
private static int solve(int[] boxes) {
if (boxes.length == 0) return 0;
if (boxes.length == 1) return max(0, boxes[0]);
int box2 = boxes[0];
int box1 = boxes[1];
for (int i = 2; i < boxes.length; i++) {
int curr = box2 + boxes[i];
box2 = max(box2, box1);
box1 = max(box1, curr);
}
return max(box1, max(box2, 0));
}
}
Am i reading the question wrong? It tells the boxes need to be sequential and also saying we cannot use a box next to what is selected.
so i need to first sort the list and then smart select boxes so that the sum is the maximum possible.
but if I follow these rules many of answers above looks wrong. what am i missing here?
Looks like I miss something here... I see answers and they looks good. but did not get how the conditions are met in the logic.
what we need to do : Select the numbers in order to have the maximum sum from collection.
Limitations.
1) sequentially placed boxes
2) Cannot select adjacent box to it, but can select any other.
So once I select a box i cannot select next one. so essentially I can skip one box but if a select a box i cannot select next box to it.
How these conditions are met.
10, 0, 0, 0, 20 -> 0, 0, 0, 10, 20 = 30? but it fails the rule since if i select 10 i cannot take 20.
8, 1, -1, 2, 20, 10 - > -1, 1, 2, 8, 10, 20 = 28. Yes i get the answer. but how it is coming in?
-1, -2, -3 = is this should be -1 and not zero since the maximum value must be the sum of one or more values from array?
int maxSum(const vector<int>& v)
{
const auto size = v.size();
if(size == 1)
{
return v[0];
}
if(size == 2)
{
return max(v[0], v[1]);
}
// Assuming no integer overflow happens, i.e. sum variable will not overflow
int sum = (1 << (8 * sizeof(int) - 1));
for(auto iter = v.begin(); iter != prev(v.end(), 2); ++iter)
{
vector<int> v1(v.end() - iter - 2);
copy(next(iter, 2), v.end(), v1.begin());
sum = max(sum, *iter + maxSum(v1));
}
return sum;
}
edited, added corner cases and updated recursion
@tryingtolearn: yes it's dp, but watch out your recursion, it has some flaws, did you verify with examples?
- Chris March 09, 2017