3 ms·
This is a very good list - I was asked a bunch of these & thankfully I was able to solve them & land the job. It's significantly harder to solve these if you re
by dxbydt 13y ago
This is a very good list - I was asked a bunch of these & thankfully I was able to solve them & land the job. It's significantly harder to solve these if you require immutability (which they did in my case, since we work with Scala)
For example, the stock price problem (https://www.interviewcake.com/question/stock-price https://www.interviewcake.com/question/stock-price ), if you insist the solution has no mutables, I really don't know how a Java/Python/C guy would approach it.
In Scala, you'd do
import math._
val s = List.fill[Int](100)((random*1000).toInt)
s./:((s.head,0)){(a,b)=>(min(b,a._1),max(a._2,b-min(b,a._1)))}._2
- bcoates 13y agoCan't you always mechanically convert an iteration into a fold like that?
- NoodleIncident 13y agoI can't really understand your version, I'm not familiar with scala. Is this somewhat equivalent? I tried to use Clojure's loop/recur but I'm too much of a noob. :( def max_profit(stocks): def r(stocks, profit, lowest): return r(stocks[1:], max([profit, stocks[0] - lowest]), min([lowest, stocks[0]])) return r(stocks[1:], 0, stocks[0])
- dxbydt 13y agoI think so. You've basically reimplemented a fold, but clojure stdlib has a built-in left fold. See line 84 https://github.com/clojure/clojure/blob/master/src/clj/clojure/core/reducers.clj https://github.com/clojure/clojure/blob/master/src/clj/cloju...