Advertisement
Guest User

Minimum Number Of Disjoint Partitions

a guest
Apr 23rd, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.03 KB | None | 0 0
  1. //Write a program that takes an integer N and an array of N different integers as input. Your program should output the minimum number of disjoint partitions of the inputted array, such that all partitions are strictly increasing sequences (Every element on the sequence except the first one is greater than the element before).
  2. //
  3. //Note: The integer N will be given in the first line, and the array of N integers will be given in the second line (Each integer separated by a single space).
  4. //
  5. //Note2: A partition is a sub array with contiguous elements of the original array.
  6. //
  7. //Note3: Two partitions are said to be disjoint if they do not share any elements with each other.
  8. //
  9. //Note4: Partitioning an array is the same as cutting an array into segments, such that the segments do not share any elements with each other and the sum of all segments is equal to the original array.
  10. //
  11. //Example:
  12. //
  13. //Case 1:
  14. //
  15. //For input given as:
  16. //
  17. //3
  18. //3 4 2
  19. //
  20. //The output of the program will be:
  21. //2
  22. //
  23. //Description of the output:
  24. //
  25. //As the original array is not a strictly increasing sequence, the answer cannot be 1. The answer can be 2 as the inputted array can be partitioned into two strictly increasing arrays {[3,4] and [2]}.
  26. //
  27. //Case 2:
  28. //
  29. //For input given as:
  30. //
  31. //3
  32. //1 2 3
  33. //
  34. //The output of the program will be:
  35. //
  36. //1
  37. //
  38. //Description of the output:
  39. //
  40. //The inputted array can be partitioned in one single array "[1, 2, 3]" as [1,2,3] is a strictly increasing sequence; so, the minimum answer is 1.
  41.  
  42. import Foundation
  43.  
  44. extension Array where Element: Comparable {
  45.   func minimumNumberOfDisjointPartitions() -> Element? {
  46.     guard var result = first else { return nil }
  47.  
  48.     var lastValue = result
  49.     for value in self {
  50.       if value < lastValue {
  51.         result = Swift.min(result, value)
  52.       }
  53.       lastValue = value
  54.     }
  55.     return result
  56.   }
  57. }
  58.  
  59. [3, 4, 2].minimumNumberOfDisjointPartitions()
  60. [1, 2, 3].minimumNumberOfDisjointPartitions()
  61. [3, 7, 4, 5, 6].minimumNumberOfDisjointPartitions()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement