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)
-
# -*- coding:utf-8 -*-
-
#import numpy
-
class Solution:
-
def FindGreatestSumOfSubArray(self, array):
-
length =len(array)
-
result =[]
-
sort_max = []
-
#1. The case of all positive numbers
-
#2. All negative numbers
-
#3. Positive and negative scenarios
-
for i in range(length-1):
-
for j in range(i+1,length):
-
(sum(array[i:j]))
-
#When all are positive, all add up to maximum
-
(sum(array))
-
#sort_ = sorted(result,reverse=False)
-
# Find the maximum
-
sort_ = max(result)
-
# Store the maximum value obtained each time in sort_max
-
sort_max.append(sort_)
-
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:
-
# -*- coding:utf-8 -*-
-
#import numpy
-
from math import*
-
class Solution:
-
def NumberOf1Between1AndN_Solution(self, n):
-
#Find the math pattern
-
#n is negative (this question is disregarded, it says it is a non-negative integer)
-
#if n < 0:
-
# return 0
-
result=0
-
tmp=n
-
base=1
-
while tmp:
-
last=tmp%10
-
tmp=tmp//10
-
result+=tmp*base
-
if last==1:
-
result+=n%base+1
-
elif last>1:
-
result+=base
-
base*=10
-
return result