avatarWilliam Pei Yuan

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

1948

Abstract

imized approach involves maintaining variables for the minimum price and the maximum profit we’ve seen so far as we iterate through the array. The idea is to calculate the profit for every day assuming we sell on that day. We update our maximum profit and minimum price so far for each day. This approach only requires a single pass, making it much more efficient.</p><div id="ee8a"><pre><span class="hljs-comment">/**

  • <span class="hljs-doctag">@param</span> {<span class="hljs-type">number[]</span>} <span class="hljs-variable">prices</span>
  • <span class="hljs-doctag">@return</span> {<span class="hljs-type">number</span>} */</span> <span class="hljs-keyword">const</span> <span class="hljs-title function_">maxProfit</span> = (<span class="hljs-params">prices</span>) => { <span class="hljs-comment">// Initializing the minPrice with the largest possible number in JavaScript</span> <span class="hljs-keyword">let</span> minPrice = <span class="hljs-title class_">Number</span>.<span class="hljs-property">MAX_VALUE</span>;

<span class="hljs-comment">// Initializing the maxProfit to 0 because the lowest profit you can make is 0 (i.e., you don't make any transaction)</span> <span class="hljs-keyword">let</span> maxProfit = <span class="hljs-number">0</span>;

<span class="hljs-comment">// Iterating over the array of prices</span> <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < prices.<span class="hljs-property">length</span>; i++) { <span class="hljs-comment">// The price of the stock on the current day</span> <span class="hljs-keyword">const</span> currentPrice = prices[i]

<span class="hljs-comment">// The profit if we sell the stock on the current day</span> <span class="hljs-keyword">const</span> currentProfit = currentPrice - minPrice

<span class="hljs-comment">// If the current price is less than the minimum

Options

price we've seen so far, update the minPrice</span> <span class="hljs-keyword">if</span> (currentPrice < minPrice) { minPrice = currentPrice; }

<span class="hljs-comment">// If the profit we can make by selling the stock on the current day is more than the maximum profit</span>
<span class="hljs-comment">// we've seen so far, update the maxProfit</span>
<span class="hljs-keyword">if</span> (currentProfit &gt; maxProfit) {
  maxProfit = currentProfit;
}

}

<span class="hljs-comment">// At the end of the loop, maxProfit will hold the maximum profit we can make by buying and selling the stock</span> <span class="hljs-keyword">return</span> maxProfit;

<span class="hljs-comment">// Test cases</span> <span class="hljs-comment">// maxProfit([7, 1, 5, 3, 6, 4]); // 5</span> <span class="hljs-comment">// maxProfit([7, 6, 4, 3, 1]); // 0</span> <span class="hljs-comment">// maxProfit([2, 4, 1]); // 2</span> <span class="hljs-comment">// maxProfit([2, 1, 2, 1, 0, 1, 2]); // 2</span> <span class="hljs-comment">// maxProfit([3, 2, 6, 5, 0, 3]); // 4 </span> };</pre></div><p id="8569">Both the brute force and optimized solutions are in place, as they don’t use extra space that scales with input size. The optimized solution is more efficient and preferred over the brute force approach in this case.</p><div id="bff4" class="link-block"> <a href="https://repljs.com/supwill/VWPIuZpd9"> <div> <div> <h2>Best Time to Buy and Sell Stock</h2> <div><h3>REPL (Read-Eval-Print-Loop) JS is a JavaScript editor for tinkering and testing.</h3></div> <div><p>repljs.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/)"></div> </div> </div> </a> </div></article></body>

Best Time to Buy and Sell Stock

Photo by Maxim Hopman on Unsplash

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one.

Time Complexity

  • Brute Force: O(n²)
  • Optimized: O(n)

Space Complexity

  • Brute Force: O(1)
  • Optimized: O(1)

Brute Force Approach

The brute force approach for this problem would be to calculate the profit for every possible pair of buy and sell days and keep track of the maximum profit. This would require nested loops and has a time complexity of O(n²).

Optimized Approach

The optimized approach involves maintaining variables for the minimum price and the maximum profit we’ve seen so far as we iterate through the array. The idea is to calculate the profit for every day assuming we sell on that day. We update our maximum profit and minimum price so far for each day. This approach only requires a single pass, making it much more efficient.

/**
 * @param {number[]} prices
 * @return {number}
 */
const maxProfit = (prices) => {
  // Initializing the minPrice with the largest possible number in JavaScript
  let minPrice = Number.MAX_VALUE;

  // Initializing the maxProfit to 0 because the lowest profit you can make is 0 (i.e., you don't make any transaction)
  let maxProfit = 0;

  // Iterating over the array of prices
  for (let i = 0; i < prices.length; i++) {
    // The price of the stock on the current day
    const currentPrice = prices[i]

  // The profit if we sell the stock on the current day
    const currentProfit = currentPrice - minPrice

    // If the current price is less than the minimum price we've seen so far, update the minPrice
    if (currentPrice < minPrice) {
      minPrice = currentPrice;
    }

    // If the profit we can make by selling the stock on the current day is more than the maximum profit
    // we've seen so far, update the maxProfit
    if (currentProfit > maxProfit) {
      maxProfit = currentProfit;
    }
  }

  // At the end of the loop, maxProfit will hold the maximum profit we can make by buying and selling the stock
  return maxProfit;

  // Test cases
  // maxProfit([7, 1, 5, 3, 6, 4]); // 5
  // maxProfit([7, 6, 4, 3, 1]); // 0
  // maxProfit([2, 4, 1]); // 2
  // maxProfit([2, 1, 2, 1, 0, 1, 2]); // 2
  // maxProfit([3, 2, 6, 5, 0, 3]); // 4 
};

Both the brute force and optimized solutions are in place, as they don’t use extra space that scales with input size. The optimized solution is more efficient and preferred over the brute force approach in this case.

Leetcode
Algorithms
Datastrucutre
Coding
Learning To Code
Recommended from ReadMedium