# Write a function max_sum that takes v a row vector of numbers & n,a positive integer as inputs.The function needs to find n consecutive elements of v whose sum is largest possible.It returns summa & index of first element of n consecutive integers.

473 views (last 30 days)
vidushi Chaudhary on 19 May 2020
Edited: DGM on 8 Mar 2023 at 6:33
%Example-[summa,index]=max_sum([1 2 3 4 5 4 3 2 1],3)
% summa=13
% index=4
function [summa,index]=max_sum(v,n)
total=v(1,1);
if n>v
summa=0;
index=-1;
else
for ii=1:length(v)
jj=ii+(n-1);
if jj<=length(v);
total=[total,sum(v(ii):v(jj))];
end
[summa,index]=max(total);
end
end
Vivek Mishra on 23 Jan 2022
would you please explain the line : total=v(1,1); and total=[total,sum(v(ii):v(jj))];

KSSV on 19 May 2020
Edited: KSSV on 19 May 2020
v = [1 2 3 4 5 4 3 2 1] ;
n = 3 ;
N = length(v) ;
sumn = zeros(1, N - n + 1); % Pre-allocation
for i = 1:N - n + 1
sumn(i) = sum(v(i:(i+n-1))) ;
end
[val,idx] = max(sumn)
Walter Roberson on 6 Aug 2021
There is a possibility that there is more than one location that is the maximum. The find() step returns all of the locations and min() of the find returns the first. Another way of doing that would be to use find(Summa==S, 1)

Willynx Vixamar on 13 Nov 2020
function [summa, index] = max_sum(v,n)
L = length(v);
S=zeros(1,L-n+1);
if n > L
summa = 0;
index = -1;
return
else
for i = 1:(L-n+1)
S(i)=sum(v(i:(i+n-1)));
end
summa = max(S);
ind = find(S == summa);
index = min(ind);
end
end

thats works，thx！

Rik on 6 Jul 2020
Edited: Rik on 30 Jul 2020
You can get a speedup by using a convolution to calculate the moving sum:
v=randi(100,2000,1);
n=10;
clc
timeit(@() option1(v,n))
ans = 3.4287e-04
timeit(@() option2(v,n))
ans = 3.5765e-05
function [val,idx]=option1(v,n) % function as suggested by KSSV
N = length(v) ;
sumn = zeros(1, N - n + 1); % Pre-allocation
for i = 1:(N - n + 1)
sumn(i) = sum(v(i:(i+n-1))) ;
end
[val,idx] = max(sumn);
end
function [val,idx]=option2(v,n)
if n>numel(v),val=0;idx=-1;return,end
sumn=conv(v,ones(n,1),'valid');
[val,idx] = max(sumn);
end
DGM on 8 Mar 2023 at 6:30
Edited: DGM on 8 Mar 2023 at 6:33
Edited only to demo the code.
An order of magnitude improvement and it's nice and concise -- what's not to like?

Bruno Luong on 29 Jul 2020
Edited: Bruno Luong on 29 Jul 2020
N=3;
v = [1 2 3 4 5 4 3 2 1];
[s,index] = maxsum(v, N)
Using this function
%% NOTE this function returns empty outputs if N>length(v)
% might be more sensitive to numerical error
function [s,index] = maxsum(v, N);
c=cumsum([0; v(:)]);
[s,index]=max(c(N+1:end)-c(1:end-N));
end
Result
s =
13
index =
4
>>
Bruno Luong on 30 Jul 2020
Edited: Bruno Luong on 30 Jul 2020
The faster timing of CONV for large array can be perhaps explained by multi-thread of the engine, that cannot be carrierd out with CUMSUM, which is sequential calculation.
TMW comes from far, the CONV in the earlier years suffered from performance. Now they have improved it greatly.
In any case a factor of 0.7 1.5 between two methods are to me essentially ... 1.
In any case your code get a vote from me.

Bruno Luong on 1 Aug 2020
function [s,index] = maxmovsum(v, N)
c = movsum(v,N);
[s,index] = max(c(1+floor(N/2):end-floor((N-1)/2)));
end

tharak infinity on 10 Nov 2020
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
Rik on 24 Jan 2022
inf is the keyword for infinity. Negative infinity is guaranteed to be the lowest value possible.

Sahil Deshpande on 17 Dec 2020
function [summa,index] = max_sum(v,n)
l=length(v);m=0;t=0;pointer=1;index=0;
%When n is larger than the length of vector v
if n>l
summa=0;
index=-1;
else
%When n is smaller than the length of vector
for a = 1:n
m=m+v(a);
end
for i = 1:(l-(n-1))
k=i;t=0;
for j = 1:n
t = t+v(k);
k=k+1;
end
if t>m
m=t;
pointer=i;
end
end
summa=m;
index=pointer;
end
I have written this code without using any inbuilt functions, just using loops. It works great!
I know it looks kinda ugly, can anyone help me optimize this code and make it shorter?
Rik on 17 Dec 2020
Have you looked at the other solutions in this thread?
Also, you already used a builtin function on your first line: length.

Shantanu Nighot on 22 Dec 2020
% Here is the working code for This Problem statement
function [summa index] = max_sum(v,n)
ii = 1;
jj = n;
% Initialize summa to zero
summa = 0;
% if n is greater than number of elements in v the return summa = 0, index = -1
if n>numel(v)
summa = 0;
index = -1;
% pro tip
% If n is equal to number of elements in v then index will always be 1 and summa = sum(v(ii:jj))
elseif n==numel(v)
summa = sum(v(ii:jj));
index = 1;
else
% while loop for calculating the sum of n elements of subsequence of v
while jj<=numel(v)
% If sum of n elements of subsequence of v is greater than the previous one
% then that sum is stored in summa and index of first element is stored in index
if sum(v(ii:jj))>summa
summa = sum(v(ii:jj));
index = ii;
end
if sum(v(ii:jj))<0 && summa == 0
summa = sum(v(ii:jj));
index = ii;
end
ii = ii + 1;
jj = jj + 1;
end
end

Eric on 22 Jul 2020
Edited: Eric on 22 Jul 2020
I came up with a function that, I think, accomplishes this task. It runs fine in my MATLAB (2020a). However, it doesn't seem to be acceptable in the Assignment Submission. Anyone know why this could be the case?
function[summa,index]=max_sum(v,n)
if n>length(v)
index=-1;
summa=0;
else
sumn=movsum(v,n);
[summa,index]=max(sumn);
index=index-1;
end
end
TANUJA GUPTA on 29 Jul 2020
@Eric, Actually when we type for example [summa,index] = max(sum); it gives the maximum value which is passed to summa, but in index it passes the index of the first no.
[Y,I] = max(X) returns the indices of the maximum values in vector I.
If the values along the first non-singleton dimension contain more
than one maximal element, the index of the first one is returned.

Capulus_love on 11 Aug 2020
Edited: Capulus_love on 11 Aug 2020
%why second problem doesn't run?
function [summa,index] = max_sum(v,n)
s = size(v); b = 0; c = 0; index = 0;
if s(2) < n
index = s(2) - n;
summa = 0;
return
end
for i = 1:s(2)-n+1
c = sum(v(i:i+n-1));
if c > b
b = c;
index = i;
else
b = b;
end
end
summa = b;
end
%Variable ind has an incorrect value.
% max_sum([ -66 31 61 60 -70 7 9 0 8 90 -54 72 12 ...
% 89 -50 4 86 -3 83 -52 ], 23) returned sum = 0 and index = -3 which is incorrect...
Rik on 11 Aug 2020
Put a breakpoint on the first line. Then use the debugger to execute your function line by line. When do you see the index go negative? When do your variable get unexpected values?
When you do that you will notice that your assumption of a column vector input isn't enforced anywhere.

LEE MUN LING on 18 Dec 2020
function [m k]=max_sum(v,n)
m=0;
if n>length(v)
k=-1;
m=0;
return
else
for k=1:((length(v)-n)+1);
while m<max(sum(v(k:((n-1)+k))));
m=max(sum(v(k:((n-1)+k))));
m=m;
k=k;
end
end
end
##### 2 CommentsShowHide 1 older comment
Rik on 18 Dec 2020
m=m; and k=k; will not do anything, so why are they in your code? Also, you posted this as an answer, but it is a question. (and you forgot to format your code as code)
Are you aware that break will only stop one loop, not all? And have you looked at the other solutions in this thread?

Rahil Ginwala on 23 Dec 2020
function [summa, index] = max_sum(v,n)
summa = 0;
i = 0;
j = v;
m = [];
c = 1;
if n>v
summa=0;
index=-1;
else
while i < n
c = numel(v(v==max(j))); % number of times the element is in the array
summa = summa + max(j)*c; % multiplying by c
b = find(v==max(j)); % find the max elemnets of v
m = [m b];% array of positions with max element
j = j(j<max(j));% remove the max number from array
i = i + 1;
end
t = sort(m);
index = t(1,1)
end
% I am not able to stop i from goigng to value 3 which gives the error for sum and index
Rahil Ginwala on 23 Dec 2020
How Can I correct this error?

Abhishek Sharma on 28 Jan 2021
% tbh, I used some help from these forum answers too
function [summa,index]=max_sum(v,n)
% first checking whether the size of row vector v is less than n or not
% if yes then print according to the given statement
if n>length(v);
summa=0;
index=-1;
else
% so you are thinking about why i took (-n+1) right?
% think of a value of size of row vector v and n
% you will get to know the answer by yourself ,example take size of v= 10 & n=10
for i=1:(length(v)-n+1);
mysum(i)=sum(v(i:i+n-1));
end
summa=max(mysum);
% I couldn't find this one, hence i used the help of this forum
x=find(mysum==summa);
index=min(x);
end

Daniel Anaya on 9 Apr 2021
%i dont know what to do. my works pretty good with positive integers. I dont know wht it has errors with negative integers
function [summa, index] = max_sum(v,n)
summa = 0;
ii = 1;
jj = n;
total = [];
if n > numel(v)
summa = 0;
index = -1;
elseif n == numel(v)
summa = sum(v(ii:jj));
index = v(1,1);
elseif n < numel(v)
for ii = 1:numel(v)
jj = ii + (n - 1);
if jj <= numel(v);
total = [total, sum(v(ii:jj))];
end
end
summa = max(total);
x = find(total == summa);
index2 = min(x);
index = v(index2);
end
Jasmine on 18 Jan 2023
Edited: Jasmine on 18 Jan 2023
it worked for me thank you

Shun Yan on 16 Apr 2021
function [a,b]=max_sum(A,B)
n=1;
C=0;
for ii = 1:(size(A,2)-B+1)
C(n)=sum(A(n:(B+n-1)));
n=n+1;
end
if B>size(A,2)
a=0;
b=-1;
else
a=max(C);
b=find(C==max(C));
end
I don't get what is variable ind, and how's sum 4 index9 wrong; can someone pls help? Thanks! ##### 2 CommentsShowHide 1 older comment
Shun Yan on 16 Apr 2021
Thanks!!

Giancarlo milon on 29 Jun 2021
function [summa,index] = max_sum(v,n)
b=1;
summa = -1000000;
%i start it with -1000000 because you ALWAYS want to overwrite your summa
index = 0;
if n > size(v)
summa = 0;
index = -1;
return
else
%this if checks for size condition if n is bigger than the size summa is 0
%and index -1
while n<=length(v);
%this will break when n = to lenght of the vector
if sum(v(b:n)) > summa
%this condition sets the sumatory of the position from b to n.
%In this case b starts in 1 and n is the input, if the sum is
%bigger than the summa it overwrites it, thats why we wanted
%always to overwrite the value summa and we started it with
%-1000000
summa = sum(v(b:n));
index = b;
end
b = b+1;
n = n+1;
%adds +1 to b and n so my positions go from 1:n to 2:n+1 to 3:n+2
%till n = the lenght and it stops
end
end
Rik on 23 Jul 2021
Your function should handle such a case. If the user needs to know how your function works and might need to edit your function, then it isn't working well.
Such limitations should be mentioned in the documentation of your function (which it currently lacks).
If you want to overwrite a variable with the lowest possible value, you should replace it with -inf.
%the number you were looking for is this:
-realmax
ans = -1.7977e+308

Ali Mohammadi on 21 Oct 2021
and this is my solution for it:
function [summa, index] = max_sum(v, n)
%creat an empty vector for cunsecutive sums, and ultimately determine the
%highest value and its index with max(w)
w = [];
ii = 1;
if n > length(v)
summa = 0
index = -1
return;
else
while n <= length (v)
w(ii) = sum(v(ii:n));
ii = ii + 1;
n = n + 1;
end
[summa, index] = max(w)
end
%I have checked, it works :)
Rik on 21 Oct 2021
What's the point of adding yet another solution? This isn't Cody.

Ujwal Dhakal on 6 Jan 2022
function [summa, index] = max_sum(v,n)
a=length(v);
sumvar=zeros(1,a-(n-1)); %preallocating a vector (you can skip this for now_go ahead and read the rest of the code)
%for invalid input
if n>a
summa=0;
index=-1;
return;
end
%assume a matrix on your own and try running i and j using the formula below, you'll get it
for i=1:(a-(n-1))
sumtemp=0;
for j=i:(n+i-1)
sumtemp=sumtemp+v(j);
end
sumvar(i)=sumtemp;%takes the sum and catenates into a vector sumvar _ that was preallocated to save some computational time
end
[summa,index_temp]=max(sumvar(:)); % if you give two output arguments to a max function, the second argument returns index of that element
index=index_temp; % the index of the maximum number in the vector sumvar happens to be also the index of our first number in the sequence
end

Yifan He on 27 Jul 2022
function [summa,index] = max_sum(v,n)
if n > length(v)
summa = 0;
index = -1;
end
if n <= length(v)
summa = sum(v(1:n));
index = 1;
for i = 1:length(v)-n
if sum(v(i+1:i+n)) > summa
summa = sum(v(i+1:i+n));
index = i+1;
else
continue;
end
end
end

function [summa,index]=max_sum(v,n)
Z=length(v);
summ=(1:Z-n+1);
if n>Z
summa=0;
index=-1;
return;
else
for i=1:(Z-n+1)
summ(i)=sum(v(i:(i+n-1)));
end
end
[summa,index]=max(summ);

Nyeche on 23 Oct 2022
function [summa, index] = max_sum (v, n)
if n < 0 || n ~= fix(n) || ~isrow(v)
error('Input must be an integer');
elseif n > length(v)
summa = 0;
index = -1;
end
total = 0;
l = length(v);
for i = 1:l-(n-1)
total(i) = sum(v(i:i+(n-1)));
summa = max(total);
index_1 = find(total == summa);
index = min(index_1);
end

Boran Yigit Usta on 16 Nov 2022
function [summa,index] = max_sum(v, n)
b = zeros(1,n);
a = find(v == max(v));
for ii = 1:n
b(ii) = max(max(v));
if find(v==b(ii),1) < a
a = find(v==b(ii),1);
end
v(find(v==max(v),1)) = 0;
end
if n > length(v)
summa = 0;
index = -1;
else
summa = sum(b);
index = a;
end
Boran Yigit Usta on 16 Nov 2022
i tested it it with variety of inputs and it works but still i get this error;
Assessment result: incorrectrandom vectors
Variable summa has an incorrect value. max_sum([ 53 -40 60 -76 -18 31 -61 67 60 75 -60 -2 60 51 -54 -10 -4 -48 -39 80 90 96 53 88 ], 5) returned sum = 429 and index = 10 which is incorrect...

Edited: DGM on 5 Mar 2023 at 18:20
function [summa,index]=max_sum(v,n)
len=length(v); %v的長度
if(n>length(v)) %n大於v的長度
summa=0;
index=-1;
return;
else
temp_sum=zeros(1,len-n+1);
for x=1:len-n+1
temp_sum(x)=sum(v(x:x+n-1));
end
[summa,index]=max(temp_sum);
end
end % end of function
DGM on 5 Mar 2023 at 18:19
Edited: DGM on 5 Mar 2023 at 18:24
Still very samey ...