leetcode || 121、Best Time to Buy and Sell Stock
2015-04-27 09:41
218 查看
problem:
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.
Hide Tags
Array Dynamic
Programming
题意:给定一支股票的价格表,决定哪天买哪天卖受益最大,卖的时间在买的后面
thinking:
(1)其实就是求一个数组元素两个元素之间的最大差值,使用后面的数减去前面的数
(2)典型的 DP思路,开一个N大小的数组,记录该位置的减去前面最小元素的差值,
最后找出差值数组的最大值即可,时间复杂度O(N)
code:
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.
Hide Tags
Array Dynamic
Programming
题意:给定一支股票的价格表,决定哪天买哪天卖受益最大,卖的时间在买的后面
thinking:
(1)其实就是求一个数组元素两个元素之间的最大差值,使用后面的数减去前面的数
(2)典型的 DP思路,开一个N大小的数组,记录该位置的减去前面最小元素的差值,
最后找出差值数组的最大值即可,时间复杂度O(N)
code:
class Solution { public: int maxProfit(vector<int>& prices) { int n=prices.size(); if(n==0) return 0; vector<int> f(n,0); int minprice=prices[0]; for(int i=0;i<n;i++) { minprice=min(minprice,prices[i]); f[i]=prices[i]-minprice; } int profit=f[0]; for(int j=0;j<n;j++) profit=max(profit,f[j]); return profit; } };
相关文章推荐
- 【小熊刷题】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
- Best Time to Buy and Sell Stock - LeetCode 121
- 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
- 【LEETCODE】121-Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock[Leetcode从零开刷]
- [leetcode]121. Best Time to Buy and Sell Stock[facebook]
- 121 Best Time to Buy and Sell Stock [Leetcode]
- LeetCode 121: Best Time to Buy and Sell Stock
- Leetcode_121_Best Time to Buy and Sell Stock