{"id":6151,"date":"2025-05-29T18:13:16","date_gmt":"2025-05-29T12:43:16","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6151"},"modified":"2025-06-05T18:46:38","modified_gmt":"2025-06-05T13:16:38","slug":"best-time-to-buy-and-sell-stock-i","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/best-time-to-buy-and-sell-stock-i\/","title":{"rendered":"Best Time to Buy and Sell Stock I"},"content":{"rendered":"\n<!-- Prism.js CSS and JS -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.css\" rel=\"stylesheet\" \/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_code-tabs-container {\n    font-family: \"Segoe UI\", sans-serif !important;\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    border: 1px solid #ddd !important;\n    border-radius: 8px !important;\n    overflow: hidden !important;\n    background-color: white !important;\n}\n\n.wp_blog_code-tabs-header {\n    background: #f7f7f7 !important;\n    display: flex !important;\n    border-bottom: 1px solid #ddd !important;\n}\n\n.wp_blog_code-tab-button {\n    flex: 1 !important;\n    padding: 10px 15px !important;\n    border: none !important;\n    background: transparent !important;\n    cursor: pointer !important;\n    font-weight: bold !important;\n    transition: background 0.2s !important;\n    color: #242B33 !important;\n}\n\n.wp_blog_code-tab-button.active {\n    background: white !important;\n    border-bottom: 3px solid #0073aa !important;\n}\n\n.wp_blog_code-tab-content {\n    display: none !important;\n    padding: 20px !important;\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content > pre {\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content.active {\n    display: block !important;\n}\n\n.wp_blog_code-tab-content pre {\n    margin: 0 !important;\n    overflow-x: auto !important;\n}\n\n.wp_blog_explanation {\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    font-family: \"Segoe UI\", sans-serif !important;\n    line-height: 1.6 !important;\n    background: white !important;\n    color: black !important;\n    padding: 1rem !important;\n    border-radius: 8px !important;\n}\n\n.wp_blog_explanation h2 {\n    color: #0073aa !important;\n    font-size: 1.5rem !important;\n    margin-bottom: 0.5rem !important;\n}\n\n.wp_blog_explanation code {\n    background: #f1f1f1 !important;\n    padding: 2px 6px !important;\n    border-radius: 4px !important;\n    font-family: monospace !important;\n}\n\n.wp_blog_explanation h1,\n.wp_blog_explanation h2,\n.wp_blog_explanation h3,\n.wp_blog_explanation h4,\n.wp_blog_explanation h5,\n.wp_blog_explanation h6,\n.wp_blog_explanation p {\n    margin-top: 10px !important;\n    margin-bottom: 10px !important;\n}\n<\/style>\n\n<!-- \u2705 START: Blog Explanation -->\n<!-- <div class=\"wp_blog_explanation\">    \n<\/div> -->\n\n<!-- \u2705 END: Blog Explanation -->\n<div class=\"wp_blog_explanation\">\n    <p>\n      You are given an array <code>prices<\/code> where <code>prices[i]<\/code> is the price of a given stock on the <code>i<sup>th<\/sup><\/code> day.\n      <br>\n      You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.\n      <br>\n      Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return <code>0<\/code>.\n    <\/p>\n  \n    <h2>Examples<\/h2>\n  \n    <p><strong>Example 1:<\/strong><br>\n      <code>Input:<\/code> prices = [7,1,5,3,6,4]<br>\n      <code>Output:<\/code> 5<br>\n      <code>Explanation:<\/code> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 &#8211; 1 = 5.\n    <\/p>\n  \n    <p><strong>Example 2:<\/strong><br>\n      <code>Input:<\/code> prices = [7,6,4,3,1]<br>\n      <code>Output:<\/code> 0<br>\n      <code>Explanation:<\/code> In this case, no transactions are done and the max profit = 0.\n    <\/p>\n  \n    <h2>Constraints<\/h2>\n    <ul>\n      <li>1 <= prices.length <= 10<sup>5<\/sup><\/li>\n      <li>0 <= prices[i] <= 10<sup>4<\/sup><\/li>\n    <\/ul>\n  \n    <h2>Approach 1 (Brute Force)<\/h2>\n    <p>Initialize <code>maxProfit = 0<\/code>.<\/p>\n    <p>Use two nested loops:<\/p>\n    <ul>\n      <li>Outer loop picks a day <code>i<\/code> to buy the stock.<\/li>\n      <li>Inner loop picks a day <code>j > i<\/code> to sell the stock.<\/li>\n      <li>For every pair <code>(i, j)<\/code>, calculate the profit: <code>prices[j] - prices[i]<\/code>.<\/li>\n      <li>If this profit is greater than <code>maxProfit<\/code>, update <code>maxProfit<\/code>.<\/li>\n    <\/ul>\n    <p>Return <code>maxProfit<\/code> after all iterations.<\/p>\n  \n    <h2>Dry Run<\/h2>\n    <pre><code>\n  Input: prices = [7, 1, 5, 3, 6, 4]\n  \n  i = 0, prices[i] = 7\n     j = 1 \u2192 1 - 7 = -6 \u2192 maxProfit = 0\n     j = 2 \u2192 5 - 7 = -2 \u2192 maxProfit = 0\n     j = 3 \u2192 3 - 7 = -4 \u2192 maxProfit = 0\n     j = 4 \u2192 6 - 7 = -1 \u2192 maxProfit = 0\n     j = 5 \u2192 4 - 7 = -3 \u2192 maxProfit = 0\n  \n  i = 1, prices[i] = 1\n     j = 2 \u2192 5 - 1 = 4 \u2192 maxProfit = 4\n     j = 3 \u2192 3 - 1 = 2 \u2192 maxProfit = 4\n     j = 4 \u2192 6 - 1 = 5 \u2192 maxProfit = 5\n     j = 5 \u2192 4 - 1 = 3 \u2192 maxProfit = 5\n  \n  i = 2, prices[i] = 5\n     j = 3 \u2192 3 - 5 = -2 \u2192 maxProfit = 5\n     j = 4 \u2192 6 - 5 = 1 \u2192 maxProfit = 5\n     j = 5 \u2192 4 - 5 = -1 \u2192 maxProfit = 5\n  \n  ... and so on.\n  \n  Final maxProfit = 5 (buy at 1, sell at 6)\n    <\/code><\/pre>\n  \n    <h2>Time and Space Complexity<\/h2>\n    <ul>\n      <li><strong>Time Complexity:<\/strong> O(n\u00b2)<br>\n        Two nested loops. For every element i, check all j > i.\n        Total comparisons = n(n-1)\/2 \u2192 O(n\u00b2)\n      <\/li>\n      <li><strong>Space Complexity:<\/strong> O(1)<br>\n        No extra data structures used. Only uses a variable <code>maxProfit<\/code>.\n      <\/li>\n    <\/ul>\n    <\/div>\n  \n<!-- \u2705 START: Code Tabs -->\n<div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\n  var maxProfit = function(prices) {\n      let maxProfit = 0;\n      for (let i = 0; i < prices.length; i++) {\n          for (let j = i + 1; j < prices.length; j++) {\n              if ((prices[j] - prices[i]) > maxProfit) {\n                  maxProfit = prices[j] - prices[i];\n              }\n          }\n      }\n      return maxProfit;\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n  class Solution {\n  public:\n      int maxProfit(vector&lt;int&gt;& prices) {\n          int maxProfit = 0;\n          for (int i = 0; i < prices.size(); i++) {\n              for (int j = i + 1; j < prices.size(); j++) {\n                  int profit = prices[j] - prices[i];\n                  if (profit > maxProfit)\n                      maxProfit = profit;\n              }\n          }\n          return maxProfit;\n      }\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n  int maxProfit(int* prices, int pricesSize) {\n      int maxProfit = 0;\n      for (int i = 0; i < pricesSize; i++) {\n          for (int j = i + 1; j < pricesSize; j++) {\n              int profit = prices[j] - prices[i];\n              if (profit > maxProfit)\n                  maxProfit = profit;\n          }\n      }\n      return maxProfit;\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\n  public class Solution {\n      public int maxProfit(int[] prices) {\n          int maxProfit = 0;\n          for (int i = 0; i < prices.length; i++) {\n              for (int j = i + 1; j < prices.length; j++) {\n                  int profit = prices[j] - prices[i];\n                  if (profit > maxProfit) {\n                      maxProfit = profit;\n                  }\n              }\n          }\n          return maxProfit;\n      }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\n  class Solution(object):\n      def maxProfit(self, prices):\n          maxProfit = 0\n          for i in range(len(prices)):\n              for j in range(i + 1, len(prices)):\n                  profit = prices[j] - prices[i]\n                  if profit > maxProfit:\n                      maxProfit = profit\n          return maxProfit\n      <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n      <pre><code class=\"language-csharp\">\n    public class Solution {\n        public int MaxProfit(int[] prices) {\n            int maxProfit = 0;\n            for (int i = 0; i < prices.Length; i++) {\n                for (int j = i + 1; j < prices.Length; j++) {\n                    int profit = prices[j] - prices[i];\n                    if (profit > maxProfit)\n                        maxProfit = profit;\n                }\n            }\n            return maxProfit;\n        }\n    }\n      <\/code><\/pre>\n    <\/div>\n    \n  <\/div>\n  \n<!-- \u2705 END: Code Tabs -->\n\n  \n\n<div class=\"wp_blog_explanation\">\n    <h2>Approach 2 (Optimal)<\/h2>\n    <ul>\n      <li>Initialize <code>min<\/code> as the first price.<\/li>\n      <li>Initialize <code>maxProfit<\/code> as 0.<\/li>\n      <li>Loop through the prices from index 1 to the end:<\/li>\n      <ul>\n        <li>If the current price minus min is greater than maxProfit, update maxProfit.<\/li>\n        <li>If the current price is less than min, update min to this new lower value.<\/li>\n      <\/ul>\n      <li>Return <code>maxProfit<\/code> at the end.<\/li>\n    <\/ul>\n  \n    <h2> Dry Run<\/h2>\n    <pre><code>\n  prices = [7, 1, 5, 3, 6, 4]\n  min = 7, maxProfit = 0\n  \n  i = 1 \u2192 prices[1] = 1\n  1 < 7 \u2192 update min = 1\n  \n  i = 2 \u2192 prices[2] = 5\n  5 - 1 = 4 > 0 \u2192 update maxProfit = 4\n  \n  i = 3 \u2192 prices[3] = 3\n  3 - 1 = 2 < 4 \u2192 no change\n  \n  i = 4 \u2192 prices[4] = 6\n  6 - 1 = 5 > 4 \u2192 update maxProfit = 5\n  \n  i = 5 \u2192 prices[5] = 4\n  4 - 1 = 3 < 5 \u2192 no change\n  \n  \u27a1\ufe0f Final maxProfit = 5 \u2705\n    <\/code><\/pre>\n  \n    <h2>Time and Space Complexity<\/h2>\n    <ul>\n      <li><strong>Time Complexity:<\/strong> O(n)<br>\n        One loop through the prices array.\n      <\/li>\n      <li><strong>Space Complexity:<\/strong> O(1)<br>\n        Only a few variables used (<code>min<\/code>, <code>maxProfit<\/code>).\n      <\/li>\n    <\/ul>\n\n<\/div>\n\n<div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\n  var maxProfit = function(prices) {\n      let min = prices[0];\n      let maxProfit = 0;\n      for (let i = 1; i < prices.length; i++) {\n          if (prices[i] - min > maxProfit) {\n              maxProfit = prices[i] - min;\n          }\n          if (prices[i] < min) {\n              min = prices[i];\n          }\n      }\n      return maxProfit;\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n  class Solution {\n  public:\n      int maxProfit(vector&lt;int&gt;& prices) {\n          int min_price = prices[0];\n          int max_profit = 0;\n          for (int i = 1; i < prices.size(); i++) {\n              if (prices[i] - min_price > max_profit)\n                  max_profit = prices[i] - min_price;\n              if (prices[i] < min_price)\n                  min_price = prices[i];\n          }\n          return max_profit;\n      }\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n  int maxProfit(int* prices, int pricesSize){\n      int min_price = prices[0];\n      int max_profit = 0;\n      for (int i = 1; i < pricesSize; i++) {\n          int profit = prices[i] - min_price;\n          if (profit > max_profit)\n              max_profit = profit;\n          if (prices[i] < min_price)\n              min_price = prices[i];\n      }\n      return max_profit;\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\n  class Solution {\n      public int maxProfit(int[] prices) {\n          int minPrice = prices[0];\n          int maxProfit = 0;\n  \n          for (int i = 1; i < prices.length; i++) {\n              int profit = prices[i] - minPrice;\n              if (profit > maxProfit) {\n                  maxProfit = profit;\n              }\n              if (prices[i] < minPrice) {\n                  minPrice = prices[i];\n              }\n          }\n  \n          return maxProfit;\n      }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\n    class Solution:\n        def maxProfit(self, prices):\n            min_price = prices[0]\n            max_profit = 0\n            for i in range(1, len(prices)):\n                profit = prices[i] - min_price\n                if profit > max_profit:\n                    max_profit = profit\n                if prices[i] < min_price:\n                    min_price = prices[i]\n            return max_profit\n      <\/code><\/pre>\n    <\/div>\n    \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n      <pre><code class=\"language-csharp\">\n    public class Solution {\n        public int MaxProfit(int[] prices) {\n            int minPrice = prices[0];\n            int maxProfit = 0;\n    \n            for (int i = 1; i < prices.Length; i++) {\n                int profit = prices[i] - minPrice;\n                if (profit > maxProfit)\n                    maxProfit = profit;\n                if (prices[i] < minPrice)\n                    minPrice = prices[i];\n            }\n    \n            return maxProfit;\n        }\n    }\n      <\/code><\/pre>\n    <\/div>\n    \n  <\/div>\n  \n<!-- \u2705 JS Tab Switch Logic -->\n<script>\ndocument.addEventListener('DOMContentLoaded', function () {\n    const buttons = document.querySelectorAll('.wp_blog_code-tab-button');\n    const contents = document.querySelectorAll('.wp_blog_code-tab-content');\n    buttons.forEach(button => {\n        button.addEventListener('click', () => {\n            const lang = button.getAttribute('data-lang');\n            buttons.forEach(btn => btn.classList.remove('active'));\n            button.classList.add('active');\n            contents.forEach(content => {\n                content.classList.toggle('active', content.getAttribute('data-lang') === lang);\n            });\n        });\n    });\n});\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[811,810],"tags":[],"class_list":{"0":"post-6151","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-data-structures-and-algorithms","7":"category-dsa"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6151","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6151"}],"version-history":[{"count":2,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6151\/revisions"}],"predecessor-version":[{"id":6441,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6151\/revisions\/6441"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6151"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6151"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6151"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}