Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Swift warmup best time to sell stock

Johnlin
November 01, 2016

Swift warmup best time to sell stock

Johnlin

November 01, 2016
Tweet

More Decks by Johnlin

Other Decks in Programming

Transcript

  1. 121. Best Time to Buy and Sell Stock • Say

    you have an array for which the ith element is the price of a given stock on day i. • څ㟬Ұݸ Arrayɼཫ໘ୈ i ݸݩૉੋ๭ࢧވථࡏୈ i ఱతၢ֨
  2. • If you were only permitted to complete at most

    one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. • ೗Ռ㟬୞ೳⴺਐߦҰ࣍ަқʢങᩯ֤Ұ࣍)ɻ ઃܭҰ ݸೳፙ౸࠷େ֫རతԋࢉ๏
  3. • Input: [7, 1, 5, 3, 6, 4] • Output:

    5 • ࠷େ֫ར = 6 - 1 = 5 • ෆੋ7-1=6 Ҽҝཁઌങ࠶ᩯ
  4. • Input: [7, 6, 4, 3, 1] • Output: 0

    • ވථҰ௚᪌ɼՄҎෆधཁަқɼॴҎ֫ར 0 ݩ
  5. class Solution { func maxProfit(_ prices: [Int]) -> Int {

    guard prices.count > 1 else { return 0 } var ࠷௿ၢ᭝ = prices.first! var ࠷େ֫ར = 0 for ၢ᭝ in prices{ ࠷େ֫ར = max(࠷େ֫ར, ၢ᭝ - ࠷௿ၢ᭝) ࠷௿ၢ᭝ = min(࠷௿ၢ᭝, ၢ᭝) } return ࠷େ֫ར } }
  6. 122. Best Time to Buy and Sell Stock II •

    Say you have an array for which the ith element is the price of a given stock on day i. • څ㟬Ұݸ Arrayɼཫ໘ୈ i ݸݩૉੋ๭ࢧވථࡏୈ i ఱతၢ֨
  7. • Design an algorithm to find the maximum profit. You

    may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). • ઃܭҰݸԋࢉ๏ိፙ౸࠷େ֫རɻ㟬૝ങᩯز࣍౎Մ Ҏɻୠੋෆೳಉ࣌ਐߦଟචަқʢങ೭લҰఆཁઌᩯ ᎃʣ
  8. • Input: [7, 1, 5, 3, 6, 4] • Output:

    7 • ࠷େ֫ར = (5-1) + (6-3) = 7
  9. class Solution { func maxProfit(_ prices: [Int]) -> Int {

    guard prices.count > 1 else { return 0 } var ័֫ར = 0 var ࡢఱతၢ᭝ = prices.first! for ၢ᭝ in prices { ័֫ར += max(0, ၢ᭝ - ࡢఱతၢ᭝) ࡢఱతၢ᭝ = ၢ᭝ } return ័֫ར } }
  10. Q&A