[Leetcode]Best Time to Buy and Sell Stock

来源:互联网 发布:灵云手写输入软件 编辑:程序博客网 时间:2024/05/16 14:17

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.

class Solution {public:    /*algorithm DP        for A[1..i],the biggest value is max(A[1...i]) - min(A[1..i-1))        time O(n) space O(1)    */    int maxProfit(vector<int> &prices) {        int maxProfit = 0,minPrice = INT_MAX;        for(int i = 1;i < prices.size();i++){            minPrice = min(minPrice,prices[i-1]);            maxProfit = max(maxProfit,prices[i] - minPrice);        }        return maxProfit;    }};


0 0
原创粉丝点击