问题
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().
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:
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.
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.
回答1:
If you're working with relatively small arrays, your algorithm is going to be fast enough. Minor improvements could be achieved by reorganizing the code a bit but nothing dramatic.
If you're working with very large arrays, then I would suggest you look into numpy. It is optimized for array wide operations and has impressive performance.
For example, you can divide all the elements in an array by their inverted position in one operation:
terms = arr / np.arange(len(arr),0,-1)
and then get cumulative sums and the first index in a single line
index = np.where(np.cumsum(terms) <= M)
来源:https://stackoverflow.com/questions/54965682/faster-algorithm-to-tailor-given-mathematical-expression