#149 Best Time to Buy and Sell Stock

本文介绍了一种寻找股票买卖最佳时机以获得最大利润的算法。该算法通过预先计算两个辅助数组,分别记录每个位置左侧的最低价格和右侧的最高价格,从而在O(n)的时间复杂度内找到最大收益。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example

Given array [3,2,3,1,2], return 1.

题目思路:

这题就是要找一个最大值和一个最小值,使得他俩的差最大。并且,最小值要在最大值的左边。

这里可以预先算两个vector:一个left_min,求的是i往左看所有数的最小值;一个right_max,求得是i往右看所有数的最大值。然后,我们遍历一遍数组,对于每个i,看right_max[i] - left_min[i],求出所有i中的最大值就是答案了。

Mycode(AC = 60ms):

class Solution {
public:
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here
        if (prices.size() <= 1) return 0;
        
        vector<int> left_min(prices);
        vector<int> right_max(prices);
        
        // get min number at left of i
        for (int i = 1; i < prices.size(); i++) {
            left_min[i] = min(left_min[i - 1], prices[i]);
        }
        
        // get max number at right of i
        for (int i = prices.size() - 2; i >= 0; i--) {
            right_max[i] = max(right_max[i + 1], prices[i]);
        }
        
        int profit = 0;
        for (int i = 0; i < prices.size(); i++) {
            profit = max(profit, right_max[i] - left_min[i]);
        }
        
        return profit;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值