[Leetcode 121, medium] Best Time to Buy and Sell Stock I

来源:互联网 发布:非线性优化的优缺点 编辑:程序博客网 时间:2024/06/05 10:00

Problem:

Say you have an array for which the ith element is the price of a given stock on day i.

(IIf 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.

Analysis:


Solutions:

C++:

(I)

    int maxProfit(vector<int>& prices)    {    int max_profit = 0;    vector<int> profits;    profits.push_back(0);    for(int i = 1; i < prices.size(); ++i)    profits.push_back(prices[i] - prices[i - 1]);    int sum_profits = 0;    for(int i = 0; i < profits.size(); ++i) {        sum_profits += profits[i];        if(sum_profits < 0)            sum_profits = 0;        else if(sum_profits > max_profit)            max_profit = sum_profits;    }        return max_profit;    }

Java:


Python:


0 0
原创粉丝点击