Python maximum interval

Asked 2 years ago, Updated 2 years ago, 17 views

def deQuote(list): for i in range(0, len(list)): list[i] = int(list[i])

def findMaxSpan(list, k): size = len(list) max = list[0]

for start in range(0, size - k + 1): sum = list[start]

for i in range(1, k): sum += list[start + i]

if sum > max: max = sum

return max list = raw_input ("Enter a list of integers: ").split() deQuote(list) k = input ("Number of intervals to obtain the maximum k-intervals: ")

max = findMaxSpan(list, k)

print "max", k",-intervals: ", max

I got the maximum interval, but it's hard to get the maximum interval.

mavVal = -99999 (int.min?) i = 0 Just spin the for j in range len(list) maxVal > Sum of intervals maxVal = interval sum i = j

return (i, i + 2) Isn't this how you do it?>

Someone explained it to me, but I don't understand ㅠ<

Please give me a clear answer.,

python

2022-09-21 22:03

1 Answers

Isn't it a code that finds the largest sum among subarrays with length k in the factor list?

def findMaxSpan(list, k):
    size = len(list)
    max = list[0] #Problem

    for start in range(0, size - k + 1):
        sum = list[start]

        for i in range(1, k):
            sum += list[start + i]

        if sum > max: #Answer
            max = sum

        return max

First of all, there is a problem with the code itself that obtains the maximum interval. If you set max=list[0] as in list=[3,-1,-3,-2] if there are negative integers in the list, the desired return value will not be displayed.

If you come to the maximum section you asked,

Given the length of the subarray k, the maximum section will be up to the index i that the subarray starts with [maximum sum], i+k-1], then you need to add a code to find i.

If sum > max is True, max is changed, and you can change the index i.

Here's how to look up values and indexes in a list with one for statement.

for idx, value in enumerate(list):


2022-09-21 22:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.