121. Best Time to Buy and Sell Stock

来源:互联网 发布:币交易平台 源码 编辑:程序博客网 时间:2024/06/07 13:01

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.

题意:根据股票每天的价格,找出最佳的买卖点,使得股票收益最大。

思路:动态规划,f(n) = max(f(n-1), a[n]-min(a[1,n-1]));

class Solution {public:int maxProfit(vector<int>& prices) {int size = prices.size();if(size < 2)    return 0;vector<int> f(size, 0);f[0] = 0;f[1] = max(0, prices[1] - prices[0]);int min = prices[0];if (prices[1] < min)min = prices[1];for (int i = 2; i < size; i++){f[i] = max(f[i - 1], prices[i] - min);if (prices[i] < min)min = prices[i];}return f[size - 1];}};





0 0