Amazon Interview Question for SDE1s


Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
1
of 3 vote

Similar question has been solved using dynamic programming at: question?id=19378664

Follows the recursive structure:
currentSum = max{A[i], max{A[i-2] + A[i], A[i-2]}, max{A[i-3] + A[i], A[i-3]}, } // i runs from 2 to N.

Full working implementation in java is given below. Give the input numbers using space as delimiter.
Eg: 1 - 1 3 8 4
1 5 3 9 4
1 2 3 4 5

import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Pattern;

public class MaxSumSubset {

	static ArrayList<Integer> input = new ArrayList<Integer>();

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		Pattern pattern = Pattern.compile(System.getProperty("line.separator")
				+ "|\\s");
		scanner.useDelimiter(pattern);

		int intval, tempMax = 0;

		while (scanner.hasNextInt()) {
			intval = scanner.nextInt();
			input.add(intval);
		}

		int[] vals = new int[input.size()];

		if (vals.length > 1) {
			vals[0] = input.get(0);
			vals[1] = Math.max(input.get(0), input.get(1));

			for (int i = 2; i < input.size(); i++) {

				tempMax = Math.max(vals[i - 2], vals[i - 2] + input.get(i));

				vals[i] = Math.max(tempMax, input.get(i));
				if (i - 3 >= 0) {

					int tempMax2 = Math.max(vals[i - 3],
							vals[i - 3] + input.get(i));
					vals[i] = Math.max(tempMax2, vals[i]);
				}
			}
		}
		tempMax = -99999999;
		for (int i = 0; i < vals.length; i++) {
			if (vals[i] > tempMax) {
				tempMax = vals[i];
			}
		}
		System.out.println("Maximum sum=" + tempMax);
	}
}

- Murali Mohan June 21, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

#include<stdio.h>
#define max(x,y) (x>y?x:y)
int findsum(int a[],int n)
{
if(n==0)
return (a[0]>0?a[0]:0);
int i,x,y,z,tem;
x=a[0]>0?a[0]:0;
y=a[1]>0?a[1]:0;
z=0;
for(i=2;i<n;i++)
{
tem=z;
z=x;
x=y;
y=(max(tem,z))+(max(a[i],0));
}
return max(x,y);
}
int main()
{
int a[]={-5,-6,-10,-40,50,-35};
int n=sizeof(a)/sizeof(a[0]);
printf("max sum=%d",findsum(a,n));
return 0;
}

- Amit June 21, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

o(n) solution and works even if array contains negative elements

- Amit June 21, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Dynamic programming with Memoization

static int MaxSumBase(int[] input)
        {
            
             Hashtable Sums = new Hashtable();
            int [] memo = new int[input.Length];
            for(int i=0; i< memo.Length;i++)
                memo[i]= int.MinValue;

             for (int i = 0; i < input.Length; i++)
                 Sums.Add(i, MaxSum(input, i, memo));
             return Max(Sums);
        }

        static int MaxSum(int[] input, int index,int []memo)
        {
            if (index >= input.Length)
                return 0;

            if(memo[index] != int.MinValue)
                return memo[index];
            Hashtable Sums = new Hashtable();
            for(int i= index+2; i< input.Length; i++)
                Sums.Add(i,MaxSum(input,i,memo));

            int maxofSums = Max(Sums);
            memo[index] = input[index] + (maxofSums != int.MinValue ? maxofSums : 0);
            return memo[index];
        }

        static int Max(Hashtable sums)
        {
            int max = int.MinValue;
            foreach (int entry in sums.Values)
                if (entry > max)
                    max = entry;
            return max;
        }

- ahmad.m.hagag June 21, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int maxSum(int A[],int n)
{
int M[n+1];
M[0]=A[0];
M[1]=A[0]>A[1]?A[0]:A[1];

for(int i=2;i<n;i++)
M[i]=M[i-1]>M[i-2]+A[i]?M[i-1]:M[i-2]+A[i]
return M[n-1];
}

- Anonymous June 23, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Would you please clarify the task: is the task to find the largest sum of consequent numbers?

- Marcello Ghali June 24, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Rather the opposite: the task is to find the largest sum using the given numbers, with the condition that no 2 numbers can be next to each other in the array. So if array is {2,4,6,8,10}, then the largest sum is sum of {2,6,10}, and that's fine because none of these 3 numbers are adjacent in the original array. If the array is {-2, -4, -6, -8, -10}, then the largest sum is simply {-2}.

- Sunny June 24, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I dont know whether this solution is appropriate or not...

if I traverse the array linearly twice, I can find the largest and second largest element respectively in O(n+n) = O(n) time.
Thus we are done with the maximum sum as the largest and second largest element gives the maximum sum.
Now if we introduce the condition while finding the second largest element I think, we are done!

Need comment from all of you!

- Sinchan Garai June 24, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

How about

public int nonContinousMax(int[] array) {
		int maxIncludedPrev = 0;
		int maxExcludedPrev = 0;
		for (int i = 0; i < array.length; i++) {
			if (i == 0) {
				maxIncludedPrev = array[i];
				continue;
			} else {
				if ((maxExcludedPrev + array[i]) > maxExcludedPrev) {
					maxExcludedPrev = maxExcludedPrev + array[i];
					maxIncludedPrev = maxExcludedPrev + maxIncludedPrev;
					maxExcludedPrev = maxIncludedPrev - maxExcludedPrev;
					maxIncludedPrev = maxIncludedPrev - maxExcludedPrev;
				} else {
					maxExcludedPrev=Math.max(maxExcludedPrev, maxIncludedPrev);
					maxIncludedPrev=maxExcludedPrev;
				}
			}
		}
		return Math.max(maxIncludedPrev, maxExcludedPrev);
	}

- cyrus June 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def maximumSum(arr):
	excl, incl = 0, arr[0]
		
	for i in range(1, len(arr)):
		new_excl = max(incl, excl)
			
	    	incl = excl + arr[i]
	   	excl = new_excl;
	  
	return max(incl, excl)

- ashishgopalhattimare July 09, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More