iT邦幫忙

2024 iThome 鐵人賽

DAY 28
0
佛心分享-刷題不只是刷題

C++刷題:LeetCode Top 100 Liked系列 第 28

Day28 Greedy 題目3:121. Best Time to Buy and Sell Stock

  • 分享至 

  • xImage
  •  

Problem :

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 transaction. If you cannot achieve any profit, return 0.

Example 1 :

Input: prices = [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.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2 :

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

核心思維 :

  1. 設置maxprice紀錄最大利潤並設置minprice紀錄最低價格
  2. 遍歷所有價格並更新minprice為當前最低價格及更新maxprice為當前價格與minprice的利潤
  3. 回傳最大利潤

程式碼 :

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        //設置maxprice紀錄最大利潤
        int maxprice = 0;
        //設置minprice紀錄最低價格
        int minprice = prices[0];
        //遍歷所有價格
        for(int i = 0; i < prices.size(); i++){
            //更新minprice為目前的最低價格
            minprice = min(minprice, prices[i]);
            //更新maxprice為當前價格與minprice之間的利潤
            maxprice = max(maxprice, prices[i] - minprice);
        }
        //回傳最大利潤
        return maxprice;
    }
};

結論 :

這題的目標是找出最大利潤,透過遍歷確定定價的陣列中可以得到的最大利潤,透過持續更新當前的最低價格,並計算當前價格相對於最低價格的利潤,最後回傳maxprice代表所能獲取的最大利潤。


上一篇
Day27 Greedy 題目2:45. Jump Game II
下一篇
Day29 Misc 題目:53. Maximum Subarray
系列文
C++刷題:LeetCode Top 100 Liked30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言