Question

Problem 3: (5 2 points) Design an algorithm that takes an array of positive integers A of length n and a positive integer T as an input and finds the largest N < T such that N can be written as a sum of some elements of A and returns such a representation of N. The complexity of the algorithms has to be O(nT). For example, for A 3,7, 10 and T 19, the output is 17 7+10, because we can make 17 out of elements of A (7+10) but we cannot make 18 or 19. So the largest N T that can be made from A is 17

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi,
Given question doesnt put any restrictions over the elements order which makes it even simpler,

here is the pseduo code for the algorithm
def fun(A,T)
sum=0;
end=0
i=0
max=0
for i<A.size

if(sum>max && sum<=T)
max=sum
if(sum+A[end]<T && end<A.size)
sum=sum+A[end]
end++
else
sum=sum-i
i++

end.
We are basically maintaining 2 pointers, and moving them together based on how the sum is varying, i,e
like in this example for input [3,7,10]
first sum becomes 3,
then adding 10 becomes it becomes 13 and max sum will be 13
then adding 17 takes it to else(since >T), where max sum will be after subtracting from end, therefore 3 will be subtracted, and then 17 will be returned
Since we are only looping through the list one time, the order is O(n) only

Thumbs up if this was helpful, otherwise let me know in comments

Add a comment
Know the answer?
Add Answer to:
Problem 3: (5 2 points) Design an algorithm that takes an array of positive integers A...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT