The subarray contains both positive and negative numbers. You have to find a maximum sum subarray such that the length of the sub-array is greater than or equal to k.

Here is my code in c++ using Kadane's algorithm.

```
#include <iostream>
using namespace std;
int main(){
int n,k;
cin >> n >> k;
int array[n];
int sum = 0;
int maxsum = 0;
int beststarts[n];
for(int i = 0;i < n; i++){
cin >> array[i];
}
for(int i = 0;i < k-1;i ++){
sum = sum+array[i];
beststarts[i] = 0;
}
for(int i = k-1;i < n; i++){ //best end search with min length;
sum = sum+array[i];
int testsum = sum;
if(i > 0){
beststarts[i] = beststarts[i-1];
}
for(int j = beststarts[i] ;i-j > k-1;j ++){
testsum = testsum - array[j];
if(testsum > sum){
beststarts[i] = j+1;
sum = testsum;
}
}
if(sum > maxsum){
maxsum = sum;
}
}
cout << maxsum;
return 0;
}
```

My code is working fine but it is very slow, and i cant think of any ways to improve my code. I have also read this question [Arrays]find longest subarray whose sum divisible by K but that is not what i want, the length can be greater than k also.

Solution based on this answer

```
#include <algorithm>
#include <iterator>
#include <iostream>
#include <numeric>
#include <ostream>
#include <utility>
#include <vector>
// __________________________________________________
template<typename RandomAccessIterator> typename std::iterator_traits<RandomAccessIterator>::value_type
max_subarr_k(RandomAccessIterator first,RandomAccessIterator last,int k)
{
using namespace std;
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
if(distance(first,last) < k)
return value_type(0);
RandomAccessIterator tail=first;
first+=k;
value_type window=accumulate(tail,first,value_type(0));
value_type max_sum=window, current_sum=window;
while(first!=last)
{
window += (*first)-(*tail) ;
current_sum = max( current_sum+(*first), window );
max_sum = max(max_sum,current_sum);
++first;
++tail;
}
return max_sum;
}
// __________________________________________________
template<typename E,int N>
E *end(E (&arr)[N])
{
return arr+N;
}
int main()
{
using namespace std;
int arr[]={1,2,4,-5,-4,-3,2,1,5,6,-20,1,1,1,1,1};
cout << max_subarr_k(arr,end(arr),4) << endl;
cout << max_subarr_k(arr,end(arr),5) << endl;
}
```

Output is:

```
14
11
```

```
int w(0);
for (int i=0; i < k; i++) w += a[i];
int run_sum(w), max_sum(w);
for (int i=k; i < n; i++) {
w = a[i] + max(w, w-a[i-k]); // window will such that it will include run_sum
run_sum = max(run_sum + a[i], w);
max_sum = max(run_sum, max_sum);
}
return max_sum;
```

Similar Questions

I need algorithm ideas for generating points in 2D space with defined minimum and maximum possible distances between points. Bassicaly, i want to find a good way to insert a point in a 2D space filled

My Question is how can i find minimum and maximum latitude and longitude of specific area (500 meter) from current location. In my case, Such like i need to get X and Y CLLocation (latitude and longit

If I have XML like: <foo> <bar id=1 score=192 /> <bar id=2 score=227 /> <bar id=3 score=105 /> ... </foo> Can I use XPath to find the minimum and maximum val

I want Minimum and Maximum Latitude and Longitude Using Current Location.Suppose i have give the area of 20km so using that latitude and Longitude i want Maximum latitude and Longitude and Minimum lat

std::string array[] = { one, two, three }; How do I find out the length of the array in code?

I have an algorithmic problem.Given k sets of integers>0(which are not the same size necessarily) ,I must pick k numbers one from each set so that the difference between the maximum value and the m

This question already has an answer here: Find length of smallest window that contains all the characters of a string in another string 8 answers There is a one question of Algorithm. Question

Recently I've been struggling with the following problem: Given an array of integers, find a minimal (shortest length) subarray that sums to at least k. Obviously this can easily be done in O(n^2). I

I’m implementing authentication in a Django site using the built-in auth module, including the built-in UserCreationForm. I’d like to set a minimum length for passwords. However, I can’t find any docu

According to this question, there's no built-in way in EF v1 to figure out the length of a field. Is there a built-in way to do so in the Entity Framework that ships with .NET 4, if so - how?

I have foreach function which calls specified function on every element which it contains. I want to get minimum from thise elements but I have no idea how to write lambda or function or even a class

What is the maximum length for a mysql user password? I'm interested in having the most secure password possible, I know that longer is better. I wasn't able to find good documentation on this. Can an

What are the maximum lengths for identifiers in BigQuery (names for projects, data sets, tables, columns)? The documentation just says string wherever these identifiers are referenced, but I can't f

This question already has an answer here: Maximum sum sublist? 6 answers Given an array of integers, how can you find two indices, i and j, such that the sum of the elements in the subarray sta

I have code that is searching for minimum and maximum values in list of lines. I need this to find center of rectangle that is bounding my complicated drawing. My part of code looks like this: if (lin

How do you get a document with the minimum or maximum value in a field in MongoDB? Similar to the MIN() or MAX() functions in MySQL, but using the NodeJS MongoDB driver. Any ideas?

I've the following array: [[499, 3], [502, 3], [502, 353], [499, 353]] They are the verteces of a rectangle. I need to find the top-left, top-right, bottom-left and bottom-right vertex. What's the be

How to find maximum and minimum value from the below table using awk command. 20 90 60 30 55 75 80 85 10 15 99 95 55 95 70 20 9 35 85 75 I want the output like max value=99 and min=9

In C#, is there a build-in-class that is intended for storing minimum and maximum values as doubles? The Point listed here http://msdn.microsoft.com/en-us/library/system.windows.point.point(v=vs.110).

I am researching the maximum subarray problem. It would appear that I haven't gotten the core idea. Let's say you have the following array: int arr[] ={10, 4, 2, 12, 16, 1} From what I understand the

I've had a look around, once again and can't find how to set the minimum and maximum dates allowed to be selected on a calendar in ASP.net with VB. I'm using Visual Studio 2010 and it's just a regular

I have an array of integers and need to find the position in the array of the maximum number along with the minimum. I have it working but it doesn't seem to be a very good way to do it. Can anyone su

I'm searching for Python code for maximum weight / minimum cost matching in a bipartite graph. I've been using the general case max weight matching code in NetworkX, but am finding it too slow for my

I don't understand how this isn't working Node* BST::Minimum(Node *curr) { if (curr->left != NULL) { Minimum(curr->left); } return curr; } I mean I already did insert fine, and printpostorder,

Here is my first question about maximum L sum and here is different and hard version of it. Problem : Given a mxn *positive* integer matrix find the minimum L sum from 1th row to the m'th row . L(4 it

I have this code in Python that finds all pairs of numbers in an array that sum to k: def two_sum_k(array, k): seen = set() out = set() for v in array: if k - v in seen: out.add((min(v, k-v), max(v, k

Let W be the weighted graph formed by taking the complete graph K5 on five vertices 1, 2, 3, 4, 5, with the weight of each edge {x, y} given by w({x; y}) = x + y. How can I find a minimum-weight spann

I have a variable unsigned char* data = MyFunction(); how to find the length of data?

To keep it simple lets say I have 3 whole numbers (integers) I know I can find the highest by using something like: if(num1 > num2 && num1 > num3) cout << num1 << endl; if(nu

What are the maximum and minimum values of a GregorianCalendar? Are they in a constant like Integer.MAX_VALUE, or maybe GregorianCalendar.get(BLAH)? In a nutshell, how can I create a GregorianCalendar

This is a facebook interview question, i came across at an online portal. Given a set S, find all the maximal subsets whose sum <= k. For example, if S = {1, 2, 3, 4, 5} and k = 7 Output is: {1, 2,

Anybody know how to set the minimum and maximum values for x-axis when running logi.hist.plot in popbio package in R? At the moment, the minimum value is defined as my minimum data value. I want it to

I need to find the minimum cut on a graph. I've been reading about flow networks, but all I can find are maximum flow algorithms such as Ford-Fulkerson, push-relabel, etc. Given the max flow-min cut t

I got stuck in one algorithm question. Please suggest me some efficient algorithm for the below problem. Question is Find numbers of subarrays whose sum is divisible by given number. My work I made on

First post & I've probably got no business being here, but here goes... How do I find the maximum and minimum values from the output of a 'for in' loop? I've tried the min() and max() and get the

Suppose we have an array of some integers (can be both +ve and -ve). We find non-empty maximum and minimum subarrays(subarrays have successive elements only) from this. My claim is that these subarray

I'm wondering what the maximum allowed length of a function name in Classic ASP (VBScript) is.

What kind of cost functions can be used in minimum cost maximum flow algorithm? Is it possible to have a cost function similar to: if flow on an edge is between [1, X], cost = FixedCost + C1 + flow *

In mysql database table I have integer field, what i want to find missing minimum value of the sequence. Please Help. 1,2,3,5,6,8,.... missing is 4

What is the maximum length of a variable name in JavaScript?

How can I find 2-approximate solution for a problem of determining a maximum subgraph with no cycles of an oriented graph? Subgraph is maximum if it contains the maximal number of edges amongst othe

What are the minimum/maximum integers in gprolog? Is there a way to reference these numbers without using a magic number?

Bentley's Programming Pearls (2nd ed.), in the chapter about the maximum subarray problem, describes its two-dimensional version: ...we are given an n × n array of reals, and we must find the maximum

I'm drawing several grayscale images in iOS. The values of grayscale image have minimum and maximum i.e. for 8 bit values in range [41,244]. I want to change minimum value or maximum value. I want to

I am trying to solve a Image matching problem by comparing the average color of pixels present in both the source and pattern image. I have reduced this problem to a sub array sum problem, but cannot

I have applied RangeValidator on TextBox. But it always shows me error : Invalid Range, though I have given minimum value 10 and maximum value 25. I want that user must not enter value whose length is

Is it possible to set the maximum length of text in a TextArea?

Folks, came across a problem... found this intersting... am modifying it a little bit just tu pep it up. Given a set of integers (range 0-500), find the minimum difference between the sum of two subs

I have two JSpinner one is for minimum and another one for maximum value set. I just want that if min is set some value then user can not enter less than minimum text field value in JSpinner of maximu

I've failed the interview. Question was: You have an array. Also, you have the start index i and end index j of subarray. It is possible to do some initialization steps once. You need return the inde