leetcode121---Best Time to Buy and Sell Stock
2015-05-28 17:41
330 查看
问题描述:
Say you have an array for which the ith element is the price of a given stock on day i.
给你一个数组,里边的第i个元素存储的是股票在第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.
只允许最多完成一次交易(买一股卖一股股票),设计算法找出最大收益。
问题求解:
利用贪心法求解。此题就是选择买入卖出股票的最大收益,分别找到价格最低和最高的一天,低进高出即可,也即找到最大增长,但是最低的一天要在最高的一天之前。时间复杂度为:O(N)。
Say you have an array for which the ith element is the price of a given stock on day i.
给你一个数组,里边的第i个元素存储的是股票在第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.
只允许最多完成一次交易(买一股卖一股股票),设计算法找出最大收益。
问题求解:
利用贪心法求解。此题就是选择买入卖出股票的最大收益,分别找到价格最低和最高的一天,低进高出即可,也即找到最大增长,但是最低的一天要在最高的一天之前。时间复杂度为:O(N)。
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if(n <= 1){ return 0; } //初始化最低价格 int minimum = prices[0]; //初始化最大收益 int max_profit = 0; for(int i=1;i<n;i++){ //从前往后,当前收益用当前价格减去此前的最低价格 int profit = prices[i] - minimum; //更新最大收益 max_profit = profit>max_profit?profit:max_profit; //更新最低价格 minimum = prices[i]<minimum?prices[i]:minimum; } return max_profit; } };
相关文章推荐
- 【LeetCode从零单排】No121 Best Time to Buy and Sell Stock
- leetcode:121. Best Time to Buy and Sell Stock(Java)解答
- 【leetcode】【121】Best Time to Buy and Sell Stock
- Leetcode:121. Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
- LeetCode - 121. Best Time to Buy and Sell Stock - 思路详解 - C++
- leetcode 121.Best Time to Buy and Sell Stock 股票买卖最佳时间
- LeetCode121 Best Time to Buy and Sell Stock
- LeetCode121:Best Time to Buy and Sell Stock
- 【小熊刷题】Best Time to Buy and Sell Stock I <leetcode 121 Java>
- LeetCode 121 Best Time to Buy and Sell Stock
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- 【LeetCode】121. Best Time to Buy and Sell Stock
- LeetCode-121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)
- leetcode 121. Best Time to Buy and Sell Stock 最大字段和问题 + DP
- 121. Best Time to Buy and Sell Stock LeetCode
- LeetCode 121-123 Best Time to Buy and Sell Stock I II III
- LeetCode - 121/122 - Best Time to Buy and Sell Stock
- leetcode——121——Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock题解