Maximum profit by buying and selling a share at most twice in Swift by Peak Valley Approach.
Nov 26, 2020
Pick Valley Approach is for determining exacts highs and lows of a trend, with a trend being classified based on a specific movement in price.
Input: price[] = {2, 30, 15, 10, 8, 25, 80}
Output: 100
Trader earns 100 as sum of 28 and 72
Buy at price 2, sell at 30, buy at 8 and sell at 80
Let start in Swift
class ViewController: UIViewController {
var price = [2, 30, 15, 10, 8, 25, 80]
var sum = 0
override func viewDidLoad() {
super.viewDidLoad()
for i in 1…price.count — 1 {
let checkDiffernce = price[i] — price[i — 1]
if (checkDiffernce > 0){
sum = sum + checkDiffernce
}
}
print(sum)
// Do any additional setup after loading the view.
}
}