程丰 發表於 2025-9-25 18:28:00

【LeetCode】121. 买卖股票的最佳时机

<h1 id="121-买卖股票的最佳时机">121. 买卖股票的最佳时机</h1>
<h2 id="题目">题目</h2>
<p>给定一个数组 prices ,它的第 i 个元素 prices 表示一支给定股票第 i 天的价格。</p>
<p>你只能选择 <code>某一天</code> 买入这只股票,并选择在 <code>未来的某一个不同的日子</code> 卖出该股票。设计一个算法来计算你所能获取的最大利润。</p>
<p>返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。</p>
<p><strong>例子</strong></p>
<p>输入:<br>
输出:5<br>
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。</p>
<blockquote>
<p>注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。</p>
</blockquote>
<h2 id="解法一-暴力计算">解法一: 暴力计算</h2>
<p>遍历所有可能性,记录最大值</p>
<p>空间复杂度:O(n)<br>
时间复杂度:O(n^2)</p>
<p>显然这个时间复杂度是不可接受</p>
<pre><code class="language-java">public int maxProfit(int[] prices) {
    if (prices == null || prices.length &lt;= 1)
      return 0;

    int n = prices.length;
    int max = 0;
    for (int i = 0; i &lt; n; i++) {
      for (int k = i + 1; k &lt; n; k++) {
            int diff = prices - prices;
            if (diff &gt; 0 &amp;&amp; diff &gt; max)
                max = diff;
      }
    }
    return max;
}
</code></pre>
<h2 id="解法二">解法二</h2>
<p>股票低买高卖,</p>
<p>假设第一天买进,后面天数买进/卖出</p>
<ol>
<li>假设买进,价格更低,假设买进min更新当前最少值</li>
<li>假设卖出
<ol>
<li>当前卖出利润更大,更新最大利润(此时最大利润当前价格 - 之前价格最低点)</li>
<li>当前卖出利润更新,则不更新</li>
</ol>
</li>
</ol>
<pre><code class="language-java">public int maxProfit(int[] prices) {
    if (prices == null || prices.length &lt;= 1)
      return 0;


    int min = prices, max = 0;
    for (int i = 1; i &lt; prices.length; i++) {
      if (prices &lt; min) {
            min = prices;
      } else if (prices - min &gt; max) {
            max = prices - min;
      }
    }
    return max;
}
</code></pre><br><br>
来源:https://www.cnblogs.com/WilsonPan/p/19111746
頁: [1]
查看完整版本: 【LeetCode】121. 买卖股票的最佳时机