Facebook Interview Question
SDE1sCountry: United States
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;
}
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;
}
import java.util.List;
public class MaximumK {
//Maximum with continuous elements
public int MaxCont(List<Integer> list) {
int currMax = list.get(0);
int maxsoFar = list.get(0);
for (int i = 1; i < list.size(); i++) {
currMax = Math.max(list.get(i), currMax + list.get(i));
maxsoFar = Math.max(currMax, maxsoFar);
}
return maxsoFar;
}
//Maximum with K-min continuous elements
public int MaxContwithK(List<Integer> list, int k) {
int curK = 0;
for (int i = 0; i < k; i++) {
curK = curK + list.get(i);
}
int currMax = curK;
int maxsoFar = curK;
for (int i = k; i < list.size(); i++) {
curK = curK - list.get(i - k) + list.get(i);
currMax = Math.max(curK, currMax + list.get(i));
maxsoFar = Math.max(currMax, maxsoFar);
}
return maxsoFar;
}
public static void main(String[] args) {
}
}
import java.util.List;
public class MaximumK {
//Maximum with continuous elements
public int MaxCont(List<Integer> list) {
int currMax = list.get(0);
int maxsoFar = list.get(0);
for (int i = 1; i < list.size(); i++) {
currMax = Math.max(list.get(i), currMax + list.get(i));
maxsoFar = Math.max(currMax, maxsoFar);
}
return maxsoFar;
}
//Maximum with K-min continuous elements
public int MaxContwithK(List<Integer> list, int k) {
int curK = 0;
for (int i = 0; i < k; i++) {
curK = curK + list.get(i);
}
int currMax = curK;
int maxsoFar = curK;
for (int i = k; i < list.size(); i++) {
curK = curK - list.get(i - k) + list.get(i);
currMax = Math.max(curK, currMax + list.get(i));
maxsoFar = Math.max(currMax, maxsoFar);
}
return maxsoFar;
}
public static void main(String[] args) {
}
}
int maxSubArray(vector<int> nums, size_t k) {
int currSum = 0;
for(size_t i = 0; i < k; i++) {
currSum += nums[i];
}
int maxSum = currSum;
int runSum = 0;
for(size_t i = k; i < nums.size(); i++) {
currSum += nums[i];
runSum += nums[i-k];
if(runSum < 0) {
currSum -= runSum;
runSum = 0;
}
if(currSum > maxSum) {
maxSum = currSum;
}
}
return maxSum;
}
I'm maintaining a Queue of all the elements in the window. I dequeue an old element and enqueue a new element to calculate the window sum.
There are 2 integers first and last that are used to identify the position of the subarray
private int MaxSubArray(int[] nums, int k)
{
int windowSum = 0, maxSum = 0; // For comparison of Maxsum
int first = 0, last = k-1; // Indexes of the max sum sub-array
Queue<int> numQueue = new Queue<int>(); // Elements in the window
// Generate sum of the first window
for (int i = 0; i < k; i++)
{
windowSum += nums[i];
numQueue.Enqueue(nums[i]);
}
maxSum = windowSum;
// Iterate through the rest of the array to find higher sum
for (int i = 1; i < nums.Length - k + 1; i++)
{
int deq = numQueue.Dequeue();
windowSum += nums[i + k - 1] - deq; // Sum of this window
numQueue.Enqueue(nums[i + k - 1]);
// If sum of this window is more than current maxSum
// then we have found a new max sum
if (windowSum > maxSum)
{
first = i;
last = i + k;
maxSum = windowSum;
}
}
return maxSum;
}
int MaxSubarray(vector<int> const &a, int k)
{
int max_sum = numeric_limits<int>::min();
if (k > 0 &&
k <= a.size())
{
int start = 0;
int sum = 0;
int tail_sum = 0;
for (int i = 0; i < a.size(); ++i) {
sum += a[i];
if (i >= k) {
tail_sum += a[i - k];
if (tail_sum <= 0) {
sum -= tail_sum;
tail_sum = 0;
start = i - k + 1;
}
}
if (i - start + 1 >= k) {
max_sum = max(max_sum, sum);
}
}
}
return max_sum;
}
This one was kept me thinking about why the condition would work for every case. The idea is to keep a window of at least k elements and two counters in one you always add elements to the right side of the window and in the other you always add elements from the left side of the window. If at some point the counter that add elements from the left side of the window becomes negative you can be sure that those elements don't contribute to compute the maximum sum and you can remove them from the window. As you don't know if by removing you are computing the maximum sum as this can happen several times you need to keep the track of that too.
Here a working version in python
def max_subarray_with_k(v, k):
running = 0
current = sum(v[:k])
max_sum = current
for x in xrange(k, len(v)):
current += v[x]
running += v[x-k]
if running < 0:
current -= running
running = 0
if current > max_sum:
max_sum = current
return max_sum
The Problem is an extension of Largest Sum Contiguous Subarray problem which can be solved using Kadane's Algorithm.
Here I put the adaptation for min-k size version (as well as the original Kadane's Algorithm, for comparison):
int MinsizeMaxSubarray(vector<int> a,int k)
{
int i,maxendhere=0,maxsofar,sumoflastk;
for(i=0;i<k;i++)maxendhere+=a[i];
maxsofar = maxendhere;
sumoflastk = maxendhere;
for(;i<a.size();i++)
{
maxendhere += a[i];
sumoflastk += a[i]-a[i-k];
if(maxendhere<sumoflastk) maxendhere = sumoflastk;
if(maxsofar<maxendhere) maxsofar = maxendhere;
}
return maxsofar;
}
int MaxSubarray(vector<int> a)
{
int maxendhere=0,maxsofar=0;
for(int i=0;i<a.size();i++)
{
maxendhere += a[i];
if(maxendhere<0) maxendhere = 0;
if(maxsofar<maxendhere) maxsofar = maxendhere;
}
return maxsofar;
}
The extension to the streaming env. is simple, using a circular list that maintains the last k elements in the stream.
The Problem is an extension of Largest Sum Contiguous Subarray problem which can be solved using Kadane's Algorithm.
Here I put the adaptation for min-k size version (as well as the original Kadane's Algorithm, for comparison):
int MinsizeMaxSubarray(vector<int> a,int k)
{
int i,maxendhere=0,maxsofar,sumoflastk;
for(i=0;i<k;i++)maxendhere+=a[i];
maxsofar = maxendhere;
sumoflastk = maxendhere;
for(;i<a.size();i++)
{
maxendhere += a[i];
sumoflastk += a[i]-a[i-k];
if(maxendhere<sumoflastk) maxendhere = sumoflastk;
if(maxsofar<maxendhere) maxsofar = maxendhere;
}
return maxsofar;
}
int MaxSubarray(vector<int> a)
{
int maxendhere=0,maxsofar=0;
for(int i=0;i<a.size();i++)
{
maxendhere += a[i];
if(maxendhere<0) maxendhere = 0;
if(maxsofar<maxendhere) maxsofar = maxendhere;
}
return maxsofar;
}
The extension to the streaming env. is simple, using a circular list that maintains the last k elements in the stream.
The Problem is an extension of Largest Sum Contiguous Subarray problem which can be solved using Kadane's Algorithm.
Here I put the adaptation for min-k size version (as well as the original Kadane's Algorithm, for comparison):
int MinsizeMaxSubarray(vector<int> a,int k)
{
int i,maxendhere=0,maxsofar,sumoflastk;
for(i=0;i<k;i++)maxendhere+=a[i];
maxsofar = maxendhere;
sumoflastk = maxendhere;
for(;i<a.size();i++)
{
maxendhere += a[i];
sumoflastk += a[i]-a[i-k];
if(maxendhere<sumoflastk) maxendhere = sumoflastk;
if(maxsofar<maxendhere) maxsofar = maxendhere;
}
return maxsofar;
}
int MaxSubarray(vector<int> a)
{
int maxendhere=0,maxsofar=0;
for(int i=0;i<a.size();i++)
{
maxendhere += a[i];
if(maxendhere<0) maxendhere = 0;
if(maxsofar<maxendhere) maxsofar = maxendhere;
}
return maxsofar;
}
The extension to the streaming env. is simple, using a circular list that maintains the last k elements in the stream.
At index i, we have to choose to extend the subarray or drop it.
When we drop it, the new subarray doesn't start from i but i-k+1,
and to make a decision (extend/drop) we have to compare between
- current_max_subarray_sum_ends_at_i (current_max + nums[i])
- and last_k_sum(from i-k+1 to i)
To achieve O(N), we should keep track of last_k_sum values (current_ksum)
and we can compute new current_ksum by: current_ksum - nums[i-k] + nums[i]
def find_max_subarray(nums, k):
if not nums: return
len_nums = len(nums)
if len_nums < k: return
if len_nums == k: return sum(nums), 0, len_nums-1
current_max = sum(nums[:k])
current_ksum = sum(nums[:k])
current_start = 0
max_sum = current_max
max_start = 0
max_end = 1
for i in range(k, len_nums):
current_ksum = current_ksum - nums[i-k] + nums[i]
if current_max + nums[i] > current_ksum: # extends
current_max = current_max + nums[i]
else: # drop, but we have to maintain the window size k
current_max = current_ksum
current_start = i-k+1
if current_max > max_sum:
max_sum = current_max
max_start = current_start
max_end = i
return max_sum, max_start, max_end
if __name__ == '__main__':
nums1 = [-4, -2, 1, -3]
nums2 = [1, 1, 1, 1, 1, 1]
print(find_max_subarray(nums1, 2))
print(find_max_subarray(nums2, 3))
- Anonymous May 13, 2017