MATLAB: 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.

error locationsoft-lock

%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

Best Answer

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)