gelita

Max profit buy/sell stocks K transactions

Mar 26th, 2020
752
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.59 KB | None | 0 0
  1. /*javascript max profit buy sell k times*/
  2.  
  3.  
  4. function buySell(arr, k){
  5.  
  6.   let prof = []
  7.   console.log(arr)
  8.   for(let i =0; i < arr.length; i++){
  9.     prof.push(0)
  10.   }
  11.   console.log("-------")
  12.   console.log(prof)
  13.  
  14.   for(let j = 0; j < k; j++){
  15.     let min = arr[0]
  16.     let max = 0
  17.     for(let i = 1; i < arr.length; i++){
  18.       min = Math.min(min, arr[i] - prof[i]) //-2
  19.       max = Math.max(max, arr[i]-min) //3, 5-(-2)
  20.       prof[i] = max
  21.     }
  22.     console.log(prof)
  23. }
  24.   return prof.pop()
  25. }
  26.  
  27. // [0,3,3, 5]
  28. //[0, 3,3, 7]
  29.  
  30. console.log(buySell([3, 3, 5, 0, 0, 3, 1, 4], 2))
  31.  
  32. //6
Advertisement
Add Comment
Please, Sign In to add comment