#149 Best Time to Buy and Sell Stock

来源:互联网 发布:数据库接口怎么开发 编辑:程序博客网 时间:2024/05/21 15:04

题目描述:

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;    }};


0 0