Write a function called max_sum that takes v, a row vector of numbers, and n, a positive integer as inputs. The function needs to find the n consecutive elements of v whose sum is the largest possible.

In other words, if v is [1 2 3 4 5 4 3 2 1] and n is 3, it will find 4 5 and 4 because their sum of 13 is the largest of any 3 consecutive elements of v. If multiple such sequences exist in v, max_sum returns the first one. The function returns summa, the sum as the first output argument and index, the index of the first element of the n consecutive ones as the second output.
I tried the follwing code but when there are two occurences for the same number, they both get removed in the same iteration and thus causes trouble.
function [summa, index] = max_sum(v,n)
summa = 0;
i = 0;
j = v;
m = [];
while i < n
summa = summa + max(j);
b = find(v==max(j));
m = [m b];
j = j(j<max(j));
i = i + 1 ;
end
t = sort(m);
index = t(1,1);
end

12 Comments

bro do you have the code?
i am using movsum and then max but what about index? how to find the index
function [summa ,index] = max_sum(V,n)
[q a] = size(V);
count = 0;
summa = 0;
if(n>a)
index = -1;
else
for ii = 1:a
if((ii+n-1)>a)
else
k = 0;
for jj = 0:(n-1)
k = k + V(ii+jj);
end
if(summa<k || count==0)
count =1;
summa = k;
index = ii;
end
end
end
end
function [summa, index] = max_sum(v,n)
summa = 0;
x = 0;
m = [];
while x < n
if length(v)<n
summa = 0;
index = -1;
else
b = find(v==max(v),n);
m = [m b];
l = sort(m);
index = l(1,1)
summa = sum(maxk(v,n))
return
end
end
Your loop does not change x or n, so you have a potentially infinite loop.
even i am not able to find the index position of the first n consequtive number which is having largest sum
function [summa, ind] = max_sum(v,n)
% If n is greater than v return the specified values
% Using return keyword exits the function so no further code is
% evaluated
if n > length(v)
summa = 0;
ind = -1;
return;
end
% Initialize summa to -inf.
% Then work through the vector, checking if each sum is larger than the
% current value of summa
summa = -inf;
ind = -1;
% Once we get to length(v)-n+1 we stop moving through the vector
for ii = 1:length(v)-n+1
currentV = v(ii:(ii+n-1));
currentSumma = sum(currentV);
% If currentSumma greater than summa, update summa and ind
if currentSumma > summa
summa = currentSumma;
ind = ii;
end
end
end
this is the right one. Logical indexing makes this simple but this it is a bit difficult to understand.
% using movsum
function [summa, index]= max_sum(v,n)
if n > length(v)
summa = 0;
index = -1;
return;
elseif n<=length(v)
a=movsum(v,[0,n-1]);
b=a(1:length(v)-n+1);
[summa,index]= max(b);
end
end
can u explain these two lines?
ii = 1:length(v)-n+1
currentV = v(ii:(ii+n-1));

 Accepted Answer

Don't use the question title to post the content of your assignment as that get truncated.
Assuming that your assigment is to find the sequence of length n of consecutive numbers with the highest sum, then I don't see how your algorithm even attempts that. You don't care about the maximum of the vector, it's completely irrevelant to the sequence sum. You want to calculate a sliding sum (i.e. first sum(v(1:n)), then sum(v(2:n+1)), etc. and find the maximum of these.
If you're allowed to use movsum, it can be trivially done in just two lines.

19 Comments

Hello, thanks for helping me out! However, can you please elaborate on how your suggestion works?
I came up with the above algorithm with the thought that if I can find the maximum of a vector and add it to summa, and then remove it from the vector and find the maximum again, as long as the condition statement evaluates to true, i might be able to fond the sum.
It works for certain vectors but it fails when there are two occurences of the same element.
Again, the maximum of the vector is completely irrelevant. For example, the maximum of the sequence
v = [4 5 6 7 3 2 10 1];
is 10, yet the subsequence of length 3 with maximum sum is [5 6 7].
Again, what you have to do is calculate a sliding sum, first 4+5+6, then 5+6+7, then 6+7+3, etc. and see which is greater. Again, you can use movsum to calculate that sliding sum (or a convolution) or a loop.
Oh I did not notice the word consecutive at all! Thanks for pointing that out!
Hello, how did you go about finding the index value?
@Yueqi Li: Please use flags only to inform admins and editors about inappropriate contents like spam or rudeness. Thanks.
@rahsut vk: Please ask specifically. This seems to be a homework question. With movsum and the max command (use the 2nd output) you can solve this in two lines of code. So what exactly is the problem?
jan i just reached this question ,can you tell me what the question is asking for i dont understand the question how sum is 13 ? and index.
@asad jaffar: Please do not let me guess, which detail is not clear to you. The question is:
Write a function called max_sum that takes v, a row vector of numbers, and n, a positive integer as inputs. The function needs to find the n consecutive elements of v whose sum is the largest possible.
So should I explain "write a function" or "called max_sum" or "takes v (row vector) and n (positive integer)" or "find the n consecutive elements" with the condition "whose sum is the largest possible"?
You need the commands movsum and max. That's enough. read the documentation of both commands. Good luck.
Jan i have found the sum but having difficulty in finding the index,i am not using any loop in it , keeping it simple ,@jan look at this [1,2,3,4,5,4,3,2,1] 4+5+4=13 ,index is 4 in the vector .what command should i use for that or anyother algorithm? Give me hint.
WALTER THE QUESTION IS THIS
[1 2 3 4 5 4 3 2 1]
sum=13
index 4
how ,well 1 2 3
2 3 4
3 4 5
4 5 4 =13 index 4
asad jaffar,
What does that output have to do with the question as explained by Jan above https://www.mathworks.com/matlabcentral/answers/444784-write-a-function-called-max_sum-that-takes-v-a-row-vector-of-numbers-and-n-a-positive-integer-as#comment_689576 ? You are not asked to display the sum of consecutive values as you go along: you are only asked to find the index. The max() call I show finds the maximum sum and puts it into the variable maxsum and the index is put into the variable maxidx . This presumes that you call max() on the vector of partial sums.
No ,its not about the index of maximum number in an array,its about starting index of maximum sum for example ([1 2 3 4 5 4 3 2 1]9) this is the example of above question mentioned and the answer is summa=25 ,index= 1. The algorithm is that a=movsum(v,n) Summa=max(a) Now if i found index of max it will give 5,but it should be 1 because it starts with 1 in an array. Another example ([1 2 3 4 5 4 3 2 1],3) Summa=13,index = 4 Now max is 5 in array but index in answer is 4 its about starting of number of sums 4+5+4=13 index of 4 in sum is 4 , kindly help me with this index thing ,give hint.
The code I posted provides the starting index of the place where the consecutive sum is maximal, provided that the input is the SUMS rather than the individual elements. For example,
vector_of_sums = v(1:end-2) + v(2:end-1) + v(3:end);
@asad jaffar: You have found out, that movsum replies a vector of the same size as the input. Then there are two ways to solve the problem:
  1. by maths: If movsum replies the sum of the surrounding n elements, you have to subtract ceil(n/2) from the index and ignore the leading and trailing elements of the sum.
  2. by specific command: instruct movsum to reply the sum only for elements, which have n neighbors: Use the 'Endpoints', 'discard' feature.
You find the latter solution, if you read the documentation. Do this, because it is unlikely, that you can guess all required details.
why you guys dont post the running code which you guys have tested
Because we don't usually give solutions to homework problems, particularly ones such as easy as this.
Spending a little bit of time reading about the movsum function, particularly the name/values optional arguments you could have figured out the solution:
function [summa, index] = max_sum(v,n)
[summa, index] = max(movsum(v, n, 'Endpoints', 'discard'));
end
Really not hard. I was wrong in my initial answer. You don't even need two lines, you need just one.
edit: I've just seen that Jan and Walter had already given you all the information required to write the above. Really you have no excuse for not figuring it out yourself.
There is also an efficient implementation with cumsum(), but that would be better with two lines of code instead of 1.
@Guillaume: Thank you for your post. I was looking for hints on the same assignment and came across your comment. It seems to be doing the job fine:
h = [6 45 9 67 -36 -34 99 64 67 8]; n = 4;
>> [summa, index] = max(movsum(h, n, 'Endpoints', 'discard'))
summa =
238
index =
7
What I don't understand is how Matlab knows what to do with 'index'. In the documentation for movsum there was no hint about what the funciton returns if you ask for two output arguments. To check that 'index' wasn't some kind of keyword; I tried the above again but used the names 'a' and 'b' instead of summa and index. As I assumed, the output was the same.
So my question: What part of the code tells matlab to output the index of the starting point of the sum in the second output argument?
@Maximilian Schmidt: movesum is called inside the function max, and it is max is called with two output arguments. So you need to read the max documentation.
A function called inside another function, like movesum inside max in your example, returns exactly one output argument as an input argument to the wrapper function, so
your example:
[summa, index] = max(movsum(h, n, 'Endpoints', 'discard'))
is exactly equivalent to
tmp = movsum(h, n, 'Endpoints', 'discard');
[summa, index] = max(tmp)

More Answers (37)

After hours of brainstorming, i finally figured it out
try this code-
function [summa, index]=max_sum(b,n)
y=length(b)
if n>y
summa=0;
index=-1;
else
[summa, index] = max(movsum(b, n, 'Endpoints', 'discard'));
end
end

6 Comments

can someone plz explain me what are movsum line is doing and how can we get index???
and also role of endpoints and discard?
plz explain me asap!!!!!
Since it's so urgent (why your question is not urgent or an emergency) what's stopping you from looking at the documentation of movsum and have all your questions answered all at once.
%approximate implementation
function r = movsum_with_discard(x, n)
nx = length(x);
r = zeros(1, nx-n+1);
for K = 1 : nx-n+1
r(K) = sum(x(K:K+n-1));
end
end
Can you explain nx-n+1 term? i did not understand why are you making a vector containing zeros of 1x nx-n+1 dimension
When you have a vector of length nx to be taken in full windows of length n, sliding along 1 at a time, then you have nx - n + 1 full windows. For example, data = [1 2 3 4 5 6 7 8 9 10], n = 7, then nx = 10, nx - n + 1 is 10 - 7 + 1 = 4, corresponding to the windows 1:7, 2:8, 3:9, 4:10
This codes is specifically for the case where you only want full windows -- which is what the 'discard' option of movsum is intended to indicate, that you want to discard any sum that was made with a window that was not full (such as 5:10 not being the full length of 7)
function [s,i] = max_sum(v,n)
s = 0; i = 0;
len = length(v);
l = len-n+1;
if n>len
s = 0;
i = -1;
else
for j=1:l
if j==1
s = sum(v(j:n));
i=1;
end
if s<sum(v(j:n))
s = sum(v(j:n));
i = j;
end
if n<len
n=n+1;
end
end
end
end
function [summa,index] = max_sum(v,n) % defining a function with name "max_sum", input augements are (v,n) and out put augemnts are [summa,index]
[r,e]=size(v); % reading the size of vector "v" to "r,e"
summa=0; % asaining 0 to summa
index=-1; % assaining -1 to index, as they asked in the question
sums=zeros(1,e-(n-1)); % creating a zro vector of requirted size. you can try itby taling two or th trial cases
if n>e % checking if n is greatr than th length of the vector so that summa and index can be rturnd as
summa=summa; % 0 and -1 respectively as askeed in the question.
index=index;
else % if n is less than the length of vctor then
for i=1:e-(n-1) % for loop to run across the length of the vector
for j=0:n-1 % for loop to run across the required number of elements to be summed
sums(i)=sums(i)+v(i+j); % elments of sums which are initially zeros are being updated step by step with th sum of 'n' numbers in vector
end
end
[s,i]=max(sums); % reading th maximum valu and its indx from sums to 's' and 'i'
summa=s;
index=i;
end
end
jan and walter take a look at this code this is giving me correct answers except for negative elements array
function [summa, index]=max_sum(b,n)
y=length(b)
q=movsum(b,n)
[maxsum,maxidx]=max(q)
summa=maxsum
index=(maxidx-floor(n/2))
if n==y
j=1
end
end
command window
max_sum([ 79 15 -18 -28 -30 52 -81 31 -74 4 57 -96],4)
y =
12
maxsum=
94 76 48 -61 -24 -87 -28 -72 -120 18 -109 -35
summa =
94
index =
1
index =
1
but i think my code is giving the right value plz take a look and tell me what to do

6 Comments

  • You're not answering the question. So please start you own question or at least continue commenting on the original answer. I will delete this non-answer in a while
  • Have you noticed that the code we post is a lot more readable than what you post. Can you please use the button to format your code.
  • Your code is wrong. once again read the documentation of movsum, particularly what happens to the window at the edges.
why you dont understand my point here ,no one do ,are guys even do coursera ,my point is clear can anyone here give an answer for this input
max_sum([ -61 -99 -35 -14 20 -82 -99 -50 -7 59 48 -86 -8 -43 -66 100 22 -96 -6 65 -14 ], 8)
lets see can do it .i am waiting .
I have posted working code in my answer above. This is getting tiresome.
i want to say sorry @guillaume the code worked thanks ,and i am sorry i said that your code is wrong ,thanks buddy .can you explain me what does endpoints and discard do how it is working i want to learn .
@asad: Again: Read the documentation of movsum:
doc movsum
Then try it by your own in the command windows, e.g.:
x = rand(1, 6)
movsum(x, 2)
movsum(x, 2, 'Endpoints', 'discard')
You asked: "are guys even do coursera" - no, of course we do not solve a course for beginners. we have done this about 20 or 30 years ago (a bold but maybe matching guess). We are not going to do exactly what you are doing only to answer very easy programming questions.
"i am waiting" - this is definitely the wrong approach. Exhaustive hints and working code have been posted some hours earlier already.
Some comments to your code:
function [summa, index]=max_sum(b,n)
y=length(b) % This is not useful
q=movsum(b,n)
[maxsum,maxidx]=max(q)
summa=maxsum % Why not directly: [summa,maxidx]=max(q)
index=(maxidx-floor(n/2))
if n==y % While j is not used anywhere, omit this
j=1
end
end
A nicer version:
function [summa, index] = max_sum(b, n)
q = movsum(b, n);
[summa, maxidx] = max(q);
index = maxidx - floor(n / 2);
end
But the result is not correct: The first and last two elements of the sum (or in general: floor(n / 2) elements) are not the sum of n elements of the input vector. See: doc movsum. A solution:
function [summa, index] = max_sum(b, n)
q = movsum(b, n);
m = floor(n / 2);
[summa, index] = max(q(m+1:end-m+1));
end
Try to understand, why q is cropped here. Instead of cropping it is smarter to let movsum exclude the marginal elements already with setting 'Endpoints' to 'discard'.
function [summa, index] = max_sum(A,n)
if length(A)<n
summa = 0;
index = -1;
else
B = maxk(A,n)
summa = sum(B);
z = zeros(1,length(B));
m = [];
for i = 1:length(B)
z = find(A==B(i));
m = [m z]
end
T = sort(m)
index = T(1,1)
end
end
function [summa,index]=max_sum(a,b)
n=length(a);
summa=0;
total=0;
if b>n
summa=0;
index=-1;
return
end
for i=1:(n-b+1)
for j=i:(b-1+i)
total=total+a(1,j);
end
if total>summa
summa=total;
index=i;
end
total=0;
end
end

2 Comments

Some simplifications:
function [summa, index] = max_sum(a, b)
n = length(a);
summa = 0;
index = -1;
if b <= n
for i = 1:(n - b + 1)
total = sum(a(i:b - 1 + i));
if total > summa
summa = total;
index = i;
end
end
end
end
function [summa, index]=max_sum(v,n)
L=length(v);
p=L-(n-1);
k=0;
t=0;
for i=1:p
z=n+k;
k=k+1;
s=0;
for d=i:z
s=s+v(d);
end
t(i)=s;
end
if (n<=L)
[summa index]=max(t);
else
summa=0;
index=-1;
end
end
function [summa,index] = max_sum(v,n)
if n>length(v)
summa = 0;
index = -1;
return
end
x = (length(v) - n) + 1;
tot =[];
t=0;
total = 0;
for k = 1:x
for i =1:n
total = total + v(t+i);
end
tot(k) = total;
t=t+1;
total = 0;
end
summa = max(tot);
ind= find(tot==max(tot));
index = ind(1);
end
I have written the code but it's showing error. Can anyone tell me what's wrong in it.
function [summa, index] = max_sum(v, m)
ii=1;
if length(v)
index=-1;
summa=0;
elseif length(v) ==n
index=1;
summa=sum(v);
else
summa=0;
start=1;
for ii =start : start +n-1
if summa < sum (v [start : start+n-1] )
summa=sum(v[ start : start +n-1] ) ;
index = start;
end
start =start +1;
if start
length(v) - n+1
break;
end
end
end

2 Comments

What is your expectation of what this code will do:
sum (v [start : start+n-1] )
?
To add to the problem Walter pointed out:
  • the function has an input m that is never used, but use the undefined variable n instead.
  • there's a ii loop that never uses ii.
  • that loops will only ever do one iteration because the if start is always going to be true and break out of it.
function [summa, index] = max_sum(v,n)
leng = length(v);
if leng < n
summa = 0;
index = -1;
else
w = [];
summa = 0;
for i = 1:leng
if summa < sum(v(i:n));
summa = sum(v(i:n));
index = i;
% x = sum(v(i:n));
%w = [w ,x];
if n < leng
n = n + 1;
%else
% summa = max(w);
% index = find(x == );
% end
end
end
end
end

1 Comment

this code has some error, wont work correctly for this case:
[summa index]=max_sum([ 45 -32 -25 27 78 -9 32 -1 -85 2 -32 -81 -32 -14 -31 46 -70 87 94 ], 15)
function [X,Y] = max_sum(v,n) % X and Y are output arguments
X = -inf; %take -inf value of X for getting minus sum
p = n;
Y = 1;
if n > length(v)
X = 0;
Y = -1;
end
for i = 1:(length(v)-(n-1))
a = sum(v(i:p));
p = p + 1;
if a > X %condition for taking maximum sum of consecutive elements of vector
X = a;
Y = i;
end
end
simple code for solution...
function [summa,index]=max_sum(v,n)
m=length(v);
if n>m
summa=0;
index=-1;
else
M = movsum(v,n,'Endpoints', 'discard')
[a,b]=max(M)
summa = a
index = b
end
end

1 Comment

I think the point of the assignment was not to use movsum() or other similar library functions, and to write the algorithm in more basic MATLAB.
I have written this code. Can anyone tell me what's wrong in it.
Error : Variable summa has an incorrect value. max_sum([ -91 -57 -45 -8 -21 8 75 -80 89 -36 59 -71 -57 14 3 88 -79 -68 -6 ], 5) returned sum = 325 and index = 7 which is incorrect...
function [s,i]=max_sum(a,b)
B = maxk(a,b)
[n m]=size(B);
[y z] = size(a);
f=[]; %empty matrix
kk=0; %counter
if z>=b; %no. of element in 'a' more than or equal to'b'.
s=sum(B)
for ii=1:z;
for jj=1:m;
if B(jj)==a(ii);
kk=kk+1;
f(kk)=ii ;
end
end
end
i=min(f)
else
s=0
i= -1
end

2 Comments

The sum that has to be returned is the deduced sum of the subset, not the sum of the entire vector.
Thanks for your response.
it is sum of deduced matrix 'B',
where B=Maxk(a,b) ( If a is a vector, then maxk returns a vector containing the k largest elements of a)
program worked for this command : [summa, index] = max_sum([1 2 3 4 5 4 3 2 1],3)
function [summa, index]=max_sum(v,n)
L=length(v);
p=L-(n-1);
k=0;
t=0;
for i=1:p
z=n+k;
k=k+1;
s=0;
for d=i:z
s=s+v(d);
end
t(i)=s;
end
if (n<=L)
[summa index]=max(t);
else
summa=0;
index=-1;
end
end
function [summa, index] = max_sum(v,n)
k =length(v);
if k==n
summa = sum(sum(v));
index =1;
return
elseif k<n
summa = 0;
index =-1;
return
else
z = length(v);
summa = 0;
index = -1;
if n <= z
for i = 1:(z - n + 1)
total = sum(v(i:n - 1 + i));
if total > summa
summa = total;
index = i;
end
end
end
end
function [summa, index] = maxsum(v,n)
summa = sum(v(1:n-1));
for j = 2:length(v) -2;
r = sum(v(j:j+n-1));
if summa<r
summa=r;
index = j;
end
end
%% this works well but in few cases it asks for some error. can any one help me to short out the problem?
function [summa,index] = max_sum(v,n)
if n>length(v)
summa = 0;
index = -1;
return;
end
x=1;
y=n;
great = -inf;
while y<=(length(v))
z = sum(v(1,x:y));
if z>great
great=z;
a=x;
x=x+1;
y=y+1;
elseif great==z
a=x-(x-a);
x=x+1;
y=y+1;
else
x=x+1;
y=y+1;
end
end
summa = great;
index = a;
end
function [summa,index]=max_sum(v,n)
len_v=length(v);summa=0;poss=[];ii=1;jj=n;
if n>len_v
summa=0;
index=-1;
return
end
while jj<=len_v
poss(ii)= sum(v(ii:jj));
[summa,index]=max(poss);
ii=ii+1;
jj=jj+1;
end
Here's my version of the code.
While the problem can be solved with movsum() in a single line, it's recommended to utilize if and for loops as a learning exercise.
function [summa, index] = max_sum(v, n)
if n > numel(v)
summa = 0;
index = -1;
else
j = n;
for i = 1:(numel(v) - n + 1)
s(i) = [sum(v(i:j))];
j = j + 1;
end
if numel(max(s)) > 1
m = max(s);
[summa index] = m(1);
else
[summa index] = max(s);
end
end
function [a, b] = max_sum(v,n)
if ~isscalar(n)||n<0||n~=fix(n)
error('n must be a positive integer')
end
[~,c]=size(v);
d=length(v);
r = zeros(1,d-n+1);
if n>c
b=-1;
a=0;
else
for k=1:(d-n+1) %from here, this is a means of movsum
r(k)=sum(v(k:k+n-1));
[a, b]=max(r);
end
end
end
You can also solve this question by using while loop if you don't know movsum function like me.Look at following code:-
function [summa , index ] = max_sum(A,n)
b = length(A);
c = zeros(1,b-n+1);
i = 1;
if b < n
summa = 0;
index = -1;
else
while n<=b && i<=b
c(1,i) = sum(A(i:n));
n = n+1;
i = i+1;
end
[summa , index ] = max(c);
end
function [summa,index]=max_sum(v,n)
summa=0;
index=0;
w=1;
[b a]=size(v);
if n>a
index=-1
summa=0;
else
if n<=a
for i=1:(a+1-n)
sum=0;
for j=1:n
sum=sum+v(w);
w=w+1;
end
w=w-n+1;
if sum>summa;
summa=sum;
index=v(i);
end
summa
index
end
end
end
end

2 Comments

You already have two loop control variables, i and j: use 2D indexing instead of doing strange things with w.
We recommend against naming a variable sum: it is very common to want to use the sum() function after having used sum as a variable.
function [summa index]=max_sum(v,n)
a=[ ];
if n<=length(v)
for i=1:length(v)-(n-1)
sum=0;
for j=i:i+n-1
sum=sum+v(j);
end
a(i)=sum;
end
summa=max(a);
g=find(a==summa);
index=g(1,1);
else
summa=0;
index=-1;
end
end
function [summa,index] = max_sum(A,n)
if length(A)< n
summa = 0;
index = -1;
return;
end
summa = -inf;
index = -1;
for i = 1:(length(A)-n+1)
total = sum(A(i:(i+n-1)));
if total > summa
summa = total;
index = i;
end
end
end
function[summa,index]=max_sum(v,n)
if size(v,2)<n
summa=0;
index=-1;
return
end
p=size(v,2)-(n-1);
k=1;
A=zeros(1,n);
summ1=zeros(1,p);
for i=1:p
jj=i;
while jj<=(i+n-1)
while k<=n
A(k)=v(jj);
jj=jj+1;
k=k+1;
end
end
summ1(i)=sum(A);
k=1;
end
summa=max(summ1);
index1=find(summ1==max(summ1));
if size(index1,2)>1
index=index1(1);
return
else
index=index1;
end
function [summa, index]=max_sum(m,n)
if numel(m)<n
summa=0;
index=-1;
else
summa=-inf;
for i=1:(numel(m)-n+1)
j=m(i:i+n-1);
maxsumma=sum(j);
if(maxsumma>summa)
summa=maxsumma;
index=i;
end
end
end
end
function [summa, ind] = max_sum(v,n)
% If n is greater than v return the specified values
% Using return keyword exits the function so no further code is
% evaluated if n > length(v) summa = 0; ind = -1;
return;
end
% Initialize summa to -inf.
% Then work through the vector, checking if each sum is larger than the
% current value of summa summa = -inf; ind = -1;
% Once we get to length(v)-n+1
we stop moving through the vector for ii = 1:length(v)-n+1
currentV = v(ii:(ii+n-1));
currentSumma = sum(currentV);
% If currentSumma greater than summa, update summa and ind
if currentSumma > summa
summa = currentSumma;
ind = ii;
end
end
end
function [summa, index]= max_sum(v,n)
if n > length(v)
summa = 0;
index = -1;
return;
elseif n<=length(v)
a=movsum(v,[0,n-1]);
b=a(1:length(v)-n+1);
[summa,index]= max(b);
end
end
function [summa, index]=max_sum(v,n)
l=length(v);
if n>l
summa=0;
index=-1;
else
p=l-n+1;
ii=0;
total=-inf;
for j=1:p
s=sum(v(j:n+ii));
ii=ii+1;
if s>total
total=s;
index=j;
else
continue;
end
end
summa=total;
end
end
function [summa,index] = max_sum(v,n)
b=zeros(1,length(v)-n+1); % initializing the b vector(only zeros) of length = length(v)-n+1
% this will decrease time taken for getting answer
if n > (length(v)) % if n is larger than length of v sum = 0 and index = -1 as per question (last line)
summa = 0 ;
index = -1;
else
for p = 1:[length(v)-n+1]
b(1,p) = sum (v(p:p+n-1)); % b(1,1)= v(1,1)+v(1,2) (if n = 2)
end % giving values to vector b using sum function
[summa index] = max(b); % if n = 2 sum should be between 2 consecutive elements.
end % if p = 2 and n = 2 sum between 2 nd and 3rd element should be considered
% p+n-1 = 2+2-1 = 3 // sum (v(2:3)) means sum of 2nd and 3rd element of vector b.
% so sum(v(p:p+n-1))
%what's wrong with my code
function [summa index]=max_sum(v,n)
index=0; summa=0;
if n > length(v)
summa= 0;
index=-1;
else
a=sort(v,'descend');
summa= sum(a(1:n));
index_row= find(v>=a(n));
index= min(index_row);
end
end

2 Comments

  • By using sort function u will get all elements in descending order
  • But according to question
  • we should keep the order of elements same.
  1. case 1 : if v = [1 2 3 4 5]; n = 2;
  2. summa is maximum of (1+2),(2+3),(3+4),(4+5)
  3. index is position where we are getting maximum sum here maximum sum is 9 so index = 4
  4. case 2 : if v = [1 2 3 4 5 ];n = 3;
  5. summa is maximum of (1+2+3),(2+3+4),(3+4+5)
  6. here maximum sum is 12 so index = 3
  7. case 3 : if v = [1 2 3 4 5 5 4 3 ];n=2;
  8. summa is maximum of (1+2),(2+3),(3+4),(4+5),(5+5),(5+4),(4+3)
  9. here maximum sum is 10 so index = 5
function [summa , index]=max_sum(v,n)
summa=sum(v(v<0));
for ii=1:(length(v)-(n-1))
t=0;
for jj=ii:(ii+(n-1))
t=t+v(jj);
end
if (t>summa)
summa=t;
index=ii;
end
end
end
function [summa, index] = max_sum(v,n)
if n > length(v)
summa = 0;
index = -1;
return;
end
summa = -inf;
index = -1;
for ii = 1:length(v)-n+1
currentV = v(ii:(ii+n-1));
currentSumma = sum(currentV);
if currentSumma > summa
summa = currentSumma;
index = ii;
end
end
end
Create a row vector named x that starts at 1, ends at 10, and contains 5 elements.
function [summa,index]=max_sum(v,n)
z=[];
if n>length(v)
summa=0;
index=-1;
return
elseif (n<=length(v))
for i=1:length(v)-(n-1)
z(i)=sum(v(i:i+(n-1)));
end
end
[summa,index]=max(z)
function [s,i] = max_sum(v,n)
s = 0; i = 0;
len = length(v);
l = len-n+1;
if n>len
s = 0;
i = -1;
else
for j=1:l
if j==1
s = sum(v(j:n));
i=1;
end
if s<sum(v(j:n))
s = sum(v(j:n));
i = j;
end
if n<len
n=n+1;
end
end
end
end
ffunction [summa index] = max_sum(A,n)
m=length(A);
if n > m
summa = 0;
index = -1;
return;
end
B = [];
q=m-(n-1);
for ii = 1:q
B=[B sum(A(ii:ii+n-1))];
end
[summa index] = max(B);
end

This question is closed.

Asked:

on 13 Feb 2019

Closed:

Rik
on 22 Jun 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!