Click here to Skip to main content
15,890,186 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Large Sub-Arrays | Practice Problems[^]

I can not solve this problem. Anyone helps me to solve this problem with an explanation?

What I have tried:

I solve this problem like this --
def solve(arr,n,m,k):
    A = []
    for _ in range(m):
        A.extend(arr)
    c = 0
    for i in range(len(A)):
        summation = 0


        for j in range(i,len(A)):
            summation+=A[j]
            if summation<=k:
                c+=1
    return c
 
t = int(input())
for _ in range(t):
    N,M,K = map(int,input().split())
    array = list(map(int,input().split()))
    out_ = solve(array,N,M,K)
    print(out_)


But I need more optimized solution with explanation. please help.
Posted
Updated 16-Jul-21 12:14pm
v2

While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.

So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
 
Share this answer
 
Comments
Ankit-Lodh 17-Jul-21 2:38am    
Thank you for your feedback, at the time of asking the question I must remember these points, at the next time.
Quote:
I need help to solve this programming question

The problem comes from a challenge site, this means that you need to be smart, and a brute force program is never the solution. You need to find ways to avoid unnecessary work, and/or find ways to reduce work.
Quote:
But I need more optimized solution with explanation. please help.

The problem is that your code is so brute force that it need a complete rewrite.
First of all, you need to understand the logic of the solution:
Try this by hand:
2
3 2 2
3 1 5
3 3 2
3 1 5
Then
2
3 1000 2
3 1 5
3 10000 2
3 1 5

Do you need to copy 1000 times the sequence and check every single possible sequence ?
Or you can find a better way?
'Better ways' is your optimization.

Every single sequence is a triangular number, it means that for a sequence of 3000, number of subsequences is 3000*3001/2= 4501500 subsequences.
Triangular number - Wikipedia[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900