Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function max_product that takes v a vector and n , a positive integer, a

ID: 3836941 • Letter: W

Question

Write a function max_product that takes v a vector and n, a positive integer, as inputs and computes the largest product of n consecutive elements of v. It returns the product and the index of the element of v that is the first term of the product. If there are multiple such products in v, the function must return the one with the smallest starting index. As an example, the following call will assign 6 to product and 3 to ind since the max 3-term product in the input vector is 2*1*3. If v has fewer than n elements, the function returns 0 and -1, respectively.

>> [product, ind] = max_product([1 2 2 1 3 1],3);

Explanation / Answer

function [product, ind] = max_product(v, n)
   product = 0;
   ind = -1;
   m = size(v, 2);
   if(m < n)
       return;
   end
   maxProduct = 0;
   maxIndex = -1;
   for i = 1:m-n+1
       tempProd = 1;
       for j = 0:n-1
           tempProd =tempProd * v(j+i);
       end
       if tempProd > maxProduct
           maxProduct = tempProd;
           maxIndex = i;
       end
   end
   product = maxProduct;
   ind = maxIndex;
end

Save this in a file named max_product.m

And then create another file with content

[product, ind] = max_product([1 2 2 1 3 1],3);
fprintf("%d %d ", product, ind);

And then run.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote