Facebook Interview Question for SDE1s


Country: United States




Comment hidden because of low score. Click to expand.
2
of 2 vote

public static int maxSum(int[] nums, int k)
    {
        if (nums.length == 0) return 0;

        int curSum = nums[0];
        int maxSum = curSum;
        int start = 0;

        for (int end = 1; end < nums.length; end++)
        {
            if (curSum <= 0)
            {
                curSum = 0;
                start = end;
            }

            if (end - start + 1 > k)
            {
                curSum -= nums[start];
                start++;
            }
            //assume for the moment that curSum >= 0
            //increment

            curSum += nums[end];

            if (curSum > maxSum) maxSum = curSum;

        }

        return maxSum;
    }

- SailingSG May 13, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I have written below code and tested for several test cases working fine -

Time complexity =~ O(n)

public static int findMaxSum(int[] ar,int k){
		int max = ar[0]; // max inititalize with first element
		int l = ar.length; // Length of array
		int sum = ar[0]; // sum included ith item
		int sum_e = 0; // Excluded ith item
		int j = 0; // starting point of k or < k items sum
		int i = 1; // index pointer
		while(i < l){
			if(i-j < k){
				sum_e = sum;
				sum = sum + ar[i];
//Used temp to find max of sum and sum_e without changing existing value of sum and 
// sum_e as these will be needed for next iteration
				int temp  = sum > sum_e ? sum : sum_e; 
				max = max > temp ? max : temp; 
				
				i++;
			}
			if(ar[j] < 0 || i-j >= k) {
				sum = sum -ar[j];
				j++;
				max = max > sum ? max : sum;
			}
			
			
			
		}
		
		return max;
	}

public static void main(String[] args) {
		// TODO Auto-generated method stub

		int[] ar0 = {-5,-10};
		int[] ar1 = {-3,10};
		int[] ar2 = {3,-10};
		int[] ar3 = {-2,5,60,-10,23};
		int[] ar4 = {6,2,4,-1,5,9,-2,10};
		
		System.out.println(findMaxSum(ar0, 4));
		System.out.println(findMaxSum(ar1, 4));
		System.out.println(findMaxSum(ar2, 4));
		System.out.println(findMaxSum(ar3, 4));
		System.out.println(findMaxSum(ar4, 4));
	}

o/p -
-5
10
3
78
22

Thanks

- azambhrgn May 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Concise version in Scala:

object MaxWindowKSum {
  
  def main(args: Array[String]): Unit = {   
    val a = Array(10, 12, 15, 18, 20, 4, 5, 9, 28)    
    println(getMaxWindowKSum(a, 3))
  }   
    
  def getMaxWindowKSum(a:Array[Int], k:Int) : Int = {            
    var max = 0
    var i = 0

    while (i + k < a.length) {            
      val sum =  a.slice(i , i + k).sum
      if (max < sum) max = sum      
      i += 1
    }
    return max
  } 
}

- guilhebl May 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int MaxSubarray(vector<int> const &a, int k)
{
	int max_sum = numeric_limits<int>::min();
	if (k > 0) {
		int start = 0;
		int sum = 0;
		for (int i = 0; i < a.size(); ++i) {
			while (i - start + 1 > k ||
				(start < i && a[start] <= 0))
			{
				sum -= a[start];
				++start;
			}
			sum += a[i];
			max_sum = max(max_sum, sum);
			if (sum <= 0) {
				sum = 0;
				start = i + 1;
			}
		}
	}
	return max_sum;
}

- Alex May 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//Time: O(N), Space: O(N)
public int maxSum(int[] arr, int k){
	for(int i = 1; i < arr.length; i++){
		arr[i] += arr[i - 1];
	}
	Deque<Integer> q = new LinkedList<Integer>();
	int maxSum = arr[0];
	q.addLast(0);
	for(int i = 1; i < k; i++){
		maxSum = Math.max(maxSum, Math.max(arr[i], arr[i] - arr[q.peekFirst()]);
		while(!q.isEmpty()){
			if(arr[i] < arr[q.peekFirst()]){
				q.pollFirst();
			}
		}
		q.addLast(i);
		
	}
	for(int i = k; i < arr.length; i++){
		while(q.peekFirst() < i - k){
			q.pollFirst();
		}
		maxSum = Math.max(maxSum,arr[i] - arr[q.peekFirst()]);
		while(!q.isEmpty()){
			if(arr[i] < arr[q.peekFirst()]){
				q.pollFirst();
			}
		}
		q.addLast(i);
	}
	return maxSum;
}

- divm01986 May 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Keep an index of the start of the segment when length of segments get above k, remove start element from sum and add new element, in this way the length of segment will always be <= k, and new elements can be checked for maximum sum.

{{

int start = 0;
int maxsum = -infinity;

for(int i = 0; i < array.length; i++)
{
if(start - i > k)
{
sum = sum - array[start];
start++;
}

sum += array[i];

if(sum > maxsum)
maxsum = sum;
if(sum < 0)
{
start = i + 1;
sum = 0;
}
}

}}}

- ziabadar4991 May 13, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Keep an index of the start of the segment when length of segments get above k, remove start element from sum and add new element, in this way the length of segment will always be <= k, and new elements can be checked for maximum sum.

int start = 0;
int maxsum = -infinity;

for(int i = 0; i < array.length; i++)
{
if(start - i > k)
{
sum = sum - array[start];
start++;
}

sum += array[i];

if(sum > maxsum)
maxsum = sum;
if(sum < 0)
{
start = i + 1;
sum = 0;
}
}

- ziabadar4991 May 13, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Time: O(n)
Space O(1)

public int maxSum(final int[] input) {
        Preconditions.checkNotNull(input, "Illegal input!");
        int maxSum = Integer.MIN_VALUE;
        int currentSum = 0;
        for (int i = 0; i < input.length; ++i) {
            currentSum = Math.max(currentSum + input[i], input[i]);
            maxSum = Math.max(currentSum, maxSum);
        }
        return maxSum;
    }

- Scavi May 13, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n) solution:

public static int maxSumWithK() {
		int[] a = { 1, 1, 1, 1, 1, 1, 1 };
		int k = 2;
		int maxSum[] = new int[a.length];
		int sum = a[0];
		maxSum[0] = sum;
		for (int i = 1; i < maxSum.length; i++) {
			sum += a[i];
			if (sum > a[i]) {
				maxSum[i] = sum;
			} else {
				maxSum[i] = a[i];
				sum = a[i];
			}
		}

		sum = 0;
		for (int i = 0; i < k; i++) {
			sum += a[i];
		}
		int max = sum;
		for (int i = k; i < maxSum.length; i++) {
			sum = sum + a[i] - a[i - k];
			if (sum + maxSum[i - k] > max)
				max = sum + maxSum[i - k];
		}
		return max;

}

- Ajay Kumar May 13, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def maxSum(self, s,k):
   begin=0
   sum=0
   max_sum=0
   for i in xrange(len(s)):
        if i-start+1 >k :
             sum = sum - s[i]
             start+=1
        sum = sum + s[i]
        if s[i] > sum :
             sum = s[i]
             start = i
        if sum > max_sum:
             max_sum = sum
   return max_sum

- deepjoarder July 20, 2017 | 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