Last active
April 16, 2019 05:31
-
-
Save twhitt14/bd88e9bd1baf539eba0b7ea83880f957 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Run in an Xcode Playground | |
let prices: [Double] = [6,0,-1,10] | |
let prices2: [Double] = [] | |
let prices3: [Double] = [1] | |
let prices4: [Double] = [6,0,-1,10,11,12,1,5,200,-2,200,32,-322,0,124,432,-1,-1000,1] | |
func solution(prices: [Double]) -> Double { | |
// the idea is to find the max between two key differences in the array: | |
// 1 - the largest number in the array minus the smallest number that precedes it | |
// 2 - the smallest number in the array minus the largest number that follows it (then times by -1 to fix the sign) | |
guard let largestNumber = prices.max(), | |
let indexOfLastOccurrenceOfLargestNumber = prices.lastIndex(of: largestNumber), | |
let smallestNumberPreviousToLastOccurenceOfLargestNumber = prices.prefix(through: indexOfLastOccurrenceOfLargestNumber).min(), | |
let smallestNumber = prices.min(), | |
let indexOfFirstOccurrenceOfSmallestNumber = prices.firstIndex(of: smallestNumber), | |
let largestNumberAfterFirstOccurenceOfSmallestNumber = prices.suffix(from: indexOfFirstOccurrenceOfSmallestNumber).max() | |
else { | |
return 0 | |
} | |
let largestNumberSubtractingSmallestPreviousNumber = largestNumber - smallestNumberPreviousToLastOccurenceOfLargestNumber | |
let smallestNumberSubtractingLargestFollowingNumber = smallestNumber - largestNumberAfterFirstOccurenceOfSmallestNumber // don't forget to flip the sign later since this will be negative due to the numbers' ordering in the naming convention | |
return max(largestNumberSubtractingSmallestPreviousNumber, -smallestNumberSubtractingLargestFollowingNumber) | |
} | |
solution(prices: prices) == 11 | |
solution(prices: prices2) == 0 | |
solution(prices: prices3) == 0 | |
solution(prices: prices4) == 1001 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment