4
\$\begingroup\$

Is there a more optimized solution to solve the stated problem?

Given an array 'arr' of 'N' elements and a number 'M', find the least index 'z' at which the equation gets satisfied. [ ] is considered as floor().

enter image description here

Code:

counts=0
ans=0
while(ans==0):
    s=0
    for i in range(counts,len(arr)):
        s+=int(arr[i]/(i+1-counts))
        if(s>M):
            break
    if((i+1)==len(arr) and s<=M):
        print(counts)
        ans=1
    counts+=1

Explanation:

  1. Check array from left to right. The first index that satisfies the condition is the answer. This is more optimized than considering from right to left.

  2. If at any time during the calculation, 's' is deemed more than M, break the loop and consider the next. This is more optimized than calculating 's' completely.

Example:

INPUT:

N=3 M=3

arr=[1 2 3]

OUTPUT:

0

This would give the answer 0 since the 0th index contains the first element to satisfy the given relation.

Thanks in advance.

\$\endgroup\$
  • 2
    \$\begingroup\$ This would be better as runnable code. Showing a definition of arr and M, and a corresponding answer would be ideal. \$\endgroup\$ – Carcigenicate Mar 2 at 21:21
  • 2
    \$\begingroup\$ Are the numbers assumed to be non-negative integers? Otherwise you could not break the loop if an intermediate sum is larger than M. – Does this come from a programming competition? If yes: could you provide a link to the contest? \$\endgroup\$ – Martin R Mar 3 at 10:47
  • \$\begingroup\$ Please, follow PEP-8 \$\endgroup\$ – belkka Mar 3 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.