MATLAB Answers


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.

Asked by Ajai Kannan on 13 Feb 2019 at 15:56
Latest activity Commented on by Ajai Kannan on 14 Feb 2019 at 12:02
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 ;
t = sort(m);
index = t(1,1);


Sign in to comment.

1 Answer

Answer by Guillaume
on 13 Feb 2019 at 16:03
 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.


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!

Sign in to comment.