web123456

Given an array of positive and negative numbers, find the number of consecutive arrays with the largest sum (array length greater than or equal to 1)

I'm trying to give a complete and concise function (python answer, but it's all in the mind, the language is not an issue) for a question I came across on Brush Cowboys.

1. Given an array with both positive and negative components, find the number of consecutive

(when all are positive, all values add up to the maximum)

(max(array) is what we want when all are negative)

  1. # -*- coding:utf-8 -*-
  2. #import numpy
  3. class Solution:
  4. def FindGreatestSumOfSubArray(self, array):
  5. length =len(array)
  6. result =[]
  7. sort_max = []
  8. #1. The case of all positive numbers
  9. #2. All negative numbers
  10. #3. Positive and negative scenarios
  11. for i in range(length-1):
  12. for j in range(i+1,length):
  13. (sum(array[i:j]))
  14. #When all are positive, all add up to maximum
  15. (sum(array))
  16. #sort_ = sorted(result,reverse=False)
  17. # Find the maximum
  18. sort_ = max(result)
  19. # Store the maximum value obtained each time in sort_max
  20. sort_max.append(sort_)
  21. return max(sort_max)

2. the number of times 1 occurs in positive integers from 1-n:

For example, if n = 11, then 1,10,11 are four occurrences of 1 (11 counts as two, and similarly, 111 counts as three)

Here it's all about finding a mathematical pattern so that the time complexity is minimized

can be generalized to any number X:

1 - 10, in their single digits, any X appears 1 time. 1 - 100, in their tens place, any X appears 10 times. 1 - 1000, in their hundreds place, any X appears 100 times. 1 - 10000, in their hundreds place, any X appears 10 times. 1 - 1000, in their hundreds place, any X appears 100 times. 1 - 10000, in their thousands place, any X appears 100 times.

........

1-10 to the i-th power, in the i-th digit to its right, any X occurs 10 (i-1) times.

The code is implemented as follows:

  1. # -*- coding:utf-8 -*-
  2. #import numpy
  3. from math import*
  4. class Solution:
  5. def NumberOf1Between1AndN_Solution(self, n):
  6. #Find the math pattern
  7. #n is negative (this question is disregarded, it says it is a non-negative integer)
  8. #if n < 0:
  9. # return 0
  10. result=0
  11. tmp=n
  12. base=1
  13. while tmp:
  14. last=tmp%10
  15. tmp=tmp//10
  16. result+=tmp*base
  17. if last==1:
  18. result+=n%base+1
  19. elif last>1:
  20. result+=base
  21. base*=10
  22. return result