本文主要是介绍Leetcode Best Time to Buy and Sell Stock,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
O(n^2)的就不用说了,一层遍历start_idx 一层遍历end_idx, 所以要在O(n)时间做的话 就是一次遍历记录两个位置,特殊点在于, start_idx总是当前最小, 答案一定的在这样的解中产生,就是 当前值减去当前最小值。
class Solution {
public:int maxProfit(vector<int>& prices) {if (prices.size() == 0) return 0;int ret = 0, cur_min = prices[0];for (int i = 1; i < prices.size(); i++) {ret = max(ret, prices[i] - cur_min);if (prices[i] < cur_min) {cur_min = min(prices[i], cur_min);}}return ret;}
};
这篇关于Leetcode Best Time to Buy and Sell Stock的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!