Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. class Solution {
  2. func maxSubArray(_ nums: [Int]) -> Int {
  3. guard let first = nums.first else {
  4. return 0
  5. }
  6. guard nums.count > 1 else {
  7. return first
  8. }
  9.  
  10. var maxSingle = Int.min
  11. var maxSoFar = Int.min
  12. var maxEndingHere = 0
  13.  
  14. for num in nums {
  15. maxEndingHere += num
  16. if maxEndingHere < 0 {
  17. maxEndingHere = 0
  18. }
  19. else if maxSoFar < maxEndingHere {
  20. maxSoFar = maxEndingHere
  21. }
  22. maxSingle = max(maxSingle, num)
  23. }
  24. return max(maxSoFar, maxSingle)
  25. }
  26. }
  27.  
  28. /*
  29. Leetcode results:
  30. -------------------------------------------------------------------------------------
  31. Runtime: 36 ms, faster than 92.37% of Swift online submissions for Maximum Subarray.
  32. Memory Usage: 20.9 MB, less than 16.67% of Swift online submissions for Maximum Subarray.
  33. -------------------------------------------------------------------------------------
  34. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement