4.9 leetcode -9 best-time-to-buy-and-sell-stock

来源:互联网 发布:linux perl 编辑:程序博客网 时间:2024/06/06 00:11
题目描述

Say you have an array for which the i th 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.


 貌似是个姊妹题,思路的话,我觉得也差不多的

答案也要简单一些

class Solution {public:    int maxProfit(vector<int> &prices) {        int nmoney = 0;        int nmoneymin = 0;        for(int i = 0;i < prices.size();i++)            {            if(i == 0)            {                nmoneymin = prices[i];            }            else                {                if(prices[i] < nmoneymin)                    nmoneymin = prices[i];                else                    {                    if((prices[i] - nmoneymin) > nmoney)                        nmoney = prices[i] - nmoneymin;                }            }                        }                return nmoney;    }};


阅读全文
0 0
原创粉丝点击