codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Practice] Buying/selling stocks #36

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

Problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
lpatmo commented 5 years ago

My JS solution:


/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
  //sliding window
  let currentProfit = 0;
  let maxProfit = 0;
  let b = 0;
  let s = 1;
  while (b < prices.length-1 && s < prices.length ) {
    if (prices[s] < prices[b]) {
      b = s;
    } else {
      currentProfit = prices[s] - prices[b];
      maxProfit = Math.max(currentProfit, maxProfit);
    }
    s++;
  }
  return maxProfit;
};