Module: Algorithmable::Cups::Stocks

Defined in:
lib/algorithmable/cups/stocks.rb

Instance Method Summary collapse

Instance Method Details

#find_max_profit(arr) ⇒ Object

another way


24
25
26
27
28
29
30
31
32
# File 'lib/algorithmable/cups/stocks.rb', line 24

def find_max_profit(arr)
  max_diff = arr[1] - arr[0]
  0.upto(arr.size).each do |i|
    (i + 1).upto(arr.size - 1).each do |j|
      max_diff = arr[j] - arr[i] if arr[j] - arr[i] > max_diff
    end
  end
  max_diff
end

#get_best_time(stocks) ⇒ Object

If you were only permitted to buy one share of the stock and sell one share of the stock, design an algorithm to find the best times to buy and sell.


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/algorithmable/cups/stocks.rb', line 6

def get_best_time(stocks)
  min = 0
  max_diff = 0
  buy = 0
  sell = 0
  0.upto(stocks.size - 1).each do |i|
    min = i if stocks[i] < stocks[min]
    diff = stocks[i] - stocks[min]
    next unless diff > max_diff
    buy = min
    sell = i
    max_diff = diff
  end
  { buy_at: buy, sell_at: sell, max_profit: max_diff }
end

#ruby_buy_and_sell_stocks(stocks) ⇒ Object

If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times.

Following is algorithm for this problem.

  1. Find the local minima and store it as starting index. If not exists, return.

  2. Find the local maxima. and store it as ending index. If we reach the end, set the end as ending index.

  3. Update the solution (Increment count of buy sell pairs)

  4. Repeat the above steps if end is not reached.

www.geeksforgeeks.org/stock-buy-sell/


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/algorithmable/cups/stocks.rb', line 51

def ruby_buy_and_sell_stocks(stocks)
  total_days = stocks.size - 1
  current_day = 0
  series_count = 0
  series = []

  while current_day < total_days
    while current_day <= total_days && stocks[current_day + 1] <= stocks[current_day]
      current_day += 1
    end

    return series if current_day == total_days

    series[series_count] = { buy: 0, sell: 0 }
    series[series_count][:buy] = current_day
    current_day += 1

    while current_day <= total_days && stocks[current_day] >= stocks[current_day - 1]
      current_day += 1
    end

    series[series_count][:sell] = current_day - 1
    series_count += 1
  end

  series
end