LeetCode 121 Best Time to Buy and Sell Stock

来源:互联网 发布:三国志9优化伴侣说明 编辑:程序博客网 时间:2024/05/22 10:44

Best Time to Buy and Sell Stock

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.

题意:在数组中找两个数使得差的绝对值最大,但是保证第二个数大于等于第一个数。 难度EASY。

class Solution {public:    int maxProfit(vector<int>& prices) {        int ans = 0;        int minn;        for(int i=0; i < prices.size(); i++)        {            int x = prices[i];            if(i==0) {                minn = x;                continue;            }            if( x > minn) ans = max(ans, x - minn);            else minn = min(minn, x);        }        return ans;    }};
0 0