LeetCode 121. Best Time to Buy and Sell Stock

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.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n=prices.size(),ans;
        int minnum=100010;
        for(int i=0;i<n;i++){
            minnum=min(minnum,prices[i]);
            ans=max(ans,prices[i]-minnum);
        }
        return ans;
    }
};

tip 记下每次遍历的最小值,用当前的price[i]-minnum来表示第i天可获的profits,max更新最大值。


版权声明:本文为m0_46229882原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。