本文主要是介绍Leetcode:72 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.
找出数组的最大值与最小值之差即可
class Solution {
public:int maxProfit(vector<int>& prices) {int res = 0;if(prices.empty())return res;int min = prices[0];for(int i = 0; i < prices.size(); i++){if(prices[i] < min)min = prices[i];if(prices[i] - min > res)res = prices[i] - min;}return res;}
};
这篇关于Leetcode:72 Best Time to Buy and Sell Stock的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!