title: How to optimize an O(N*M) to be O(n**2)?
body: <p>I am trying to solve USACO's Milking Cows problem. The problem statement is here: <a href="https://train.usaco.org/usacoprob2?S=milk2&amp;a=n3lMlotUxJ1" rel="nofollow noreferrer">https://train.usaco.org/usacoprob2?S=milk2&amp;a=n3lMlotUxJ1</a></p>
  
  <p>Given a series of intervals in the form of a 2d array, I have to find the longest interval and the longest interval in which no milking was occurring. </p>
  
  <p>Ex. Given the array <code>[[500,1200],[200,900],[100,1200]]</code>, the longest interval would be 1100 as there is continuous milking and the longest interval without milking would be 0 as there are no rest periods. </p>
  
  <p>I have tried looking at whether utilizing a dictionary would decrease run times but I haven't had much success. </p>
  
  <pre><code>f = open('milk2.in', 'r')
  w = open('milk2.out', 'w')
  
  #getting the input
  farmers = int(f.readline().strip())
  schedule = []
  for i in range(farmers):
      schedule.append(f.readline().strip().split())
  
  
  #schedule = data
  minvalue = 0
  maxvalue = 0
  
  #getting the minimums and maximums of the data 
  for time in range(farmers):
      schedule[time][0] = int(schedule[time][0])
      schedule[time][1] = int(schedule[time][1])
      if (minvalue == 0):
          minvalue = schedule[time][0]
      if (maxvalue == 0):
          maxvalue = schedule[time][1]
      minvalue = min(schedule[time][0], minvalue)
      maxvalue = max(schedule[time][1], maxvalue)
  
  filled_thistime = 0
  filled_max = 0
  
  empty_max = 0
  empty_thistime = 0
  
  #goes through all the possible items in between the minimum and the maximum
  for point in range(minvalue, maxvalue):
      isfilled = False
      #goes through all the data for each point value in order to find the best values
      for check in range(farmers):
          if point &gt;= schedule[check][0] and point &lt; schedule[check][1]:
              filled_thistime += 1
              empty_thistime = 0
              isfilled = True
              break
      if isfilled == False:
          filled_thistime = 0
          empty_thistime += 1
      if (filled_max &lt; filled_thistime) : 
          filled_max = filled_thistime 
      if (empty_max &lt; empty_thistime) : 
          empty_max = empty_thistime 
  print(filled_max)
  print(empty_max)
  if (filled_max &lt; filled_thistime):
      filled_max = filled_thistime
  
  w.write(str(filled_max) + " " + str(empty_max) + "\n")
  f.close()
  w.close()
  </code></pre>
  
  <p>The program works fine, but I need to decrease the time it takes to run. </p>