alestane

Value stream

May 26th, 2016
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.22 KB | None | 0 0
  1. public class Losses: SequenceType {
  2.     private var source: Generator?;
  3.    
  4.     public typealias Generator = AnyGenerator<Int>
  5.    
  6.     init <S: SequenceType where S.Generator.Element == Int>(_ _source: S) {
  7.         source = Generator(_source.generate())
  8.     }
  9.    
  10.     public func generate() -> Generator {
  11.         var peak: Int = -1
  12.         var trough: Int = -1
  13.        
  14.         return AnyGenerator {
  15.             if let source = self.source {
  16.                 while let v = source.next() {
  17.                     if v > peak {
  18.                         let loss = trough - peak
  19.                         peak = v
  20.                         trough = peak
  21.                         if loss < 0 {
  22.                             return loss
  23.                         }
  24.                         continue
  25.                     }
  26.                     if v < trough { trough = v }
  27.                 }
  28.                 self.source = nil
  29.                 return trough - peak
  30.             } else {
  31.                 return nil
  32.             }
  33.         }
  34.     }
  35. }
  36.  
  37. let n = Int(readLine()!)!
  38. var input = (readLine()!).characters.split{$0 == " "}
  39. var lossSeq = Losses(input.map { return Int(String($0)) })
  40. var minimum = minElement(lossSeq)
  41. print(minimum)
Add Comment
Please, Sign In to add comment