fork download
  1. import operator
  2.  
  3. def max_saw(arr):
  4. if len(arr) < 3:
  5. return len(arr)
  6. n, nmax = 2, 2
  7. for i in range(2, len(arr)):
  8. if (arr[i] > arr[i-1]) ^ (arr[i-1] > arr[i-2]):
  9. n += 1
  10. else:
  11. n = 2
  12. if n > nmax:
  13. nmax = n
  14. return nmax
  15.  
  16. def max_saw_op(arr):
  17. if len(arr) < 3:
  18. return len(arr)
  19. n, nmax = 2, 2
  20. ops = [operator.gt, operator.lt]
  21. op = ops[arr[1] > arr[0]]
  22. for i in range(2, len(arr)):
  23. if op(arr[i], arr[i-1]):
  24. n += 1
  25. op = ops[1 - ops.index(op)]
  26. else:
  27. op = ops[arr[i] > arr[i-1]]
  28. n = 2
  29. if n > nmax:
  30. nmax = n
  31. return nmax
  32.  
  33. def max_saw_min(arr):
  34. n, nmax = 2, 2
  35. for i in range(2, len(arr)):
  36. n = n + 1 if (arr[i] > arr[i-1]) ^ (arr[i-1] > arr[i-2]) else 2
  37. nmax = max(n, nmax)
  38. return nmax
  39.  
  40. print(max_saw([1,2,3]), end=" ")
  41. print(max_saw([5, 7, 6, 3, 4, 2, 7, 1, 8, 9, 4, 5]), end=" ")
  42. print(max_saw([1, -2, 3, -4, 5]))
  43. print(max_saw_op([1,2,3]), end=" ")
  44. print(max_saw_op([5, 7, 6, 3, 4, 2, 7, 1, 8, 9, 4, 5]), end=" ")
  45. print(max_saw_op([1, -2, 3, -4, 5]))
  46. print(max_saw_min([1,2,3]), end=" ")
  47. print(max_saw_min([5, 7, 6, 3, 4, 2, 7, 1, 8, 9, 4, 5]), end=" ")
  48. print(max_saw_min([1, -2, 3, -4, 5]))
Success #stdin #stdout 0.01s 9992KB
stdin
Standard input is empty
stdout
2 7 5
2 7 5
2 7 5