Week1 121.Best Time to Buy and Sell Stock

来源:互联网 发布:混合高斯算法 编辑:程序博客网 时间:2024/06/05 11:18

题目

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.

分析

给出一个数组,其中第i个元素是第i天股票的价格,求出通过一次交易能得到最大的利润(先买才能后卖,所以卖价在数组的位置必须在买价在数组的位置),因此应该要遍历数组,设置两个变量,一个是result(初始化为0),另一个是min(记录数组的最小值),然后每次用数组的值减去min的值,如果大于result,则将result赋值为该值。

代码

class Solution {public:    int maxProfit(vector<int>& prices) {        int result = 0, min;        if(!prices.empty()) min = prices[0];        for(int i = 1;i < prices.size(); ++i) {            if(prices[i] < min) {                min = prices[i];            } else {                int new_profit  = prices[i] - min;                if(new_profit > result) result = new_profit;            }        }        return result;    }};


原创粉丝点击