leetcode_121 Best Time to Buy and Sell Stock
2016-04-09 21:48
381 查看
题目分析:
用一个数组表示股票每天的价格,数组中第i个数表示股票在第i天的价格。若只允许进行一次交易,即只允许买一只股票,并卖掉,求在这些田中如何进行买卖交易获得的收益最大。
解题思路:
动态规划求解
一遍遍历数组,用一个数记录从开始到现在出现过的最低价格,作为买入价格,假设当天售出,计算收益,如果收益大于最大收益,则更新最大收益。遍历完整个数组后得到最后的最大收益。时间复杂度为O(n),空间复杂度为O(1)。
实现程序
用一个数组表示股票每天的价格,数组中第i个数表示股票在第i天的价格。若只允许进行一次交易,即只允许买一只股票,并卖掉,求在这些田中如何进行买卖交易获得的收益最大。
解题思路:
动态规划求解
一遍遍历数组,用一个数记录从开始到现在出现过的最低价格,作为买入价格,假设当天售出,计算收益,如果收益大于最大收益,则更新最大收益。遍历完整个数组后得到最后的最大收益。时间复杂度为O(n),空间复杂度为O(1)。
实现程序
class Solution { public: int maxProfit(vector<int> &prices) { if (prices.size() < 2) return 0; // 记录最大收益 int profit = 0; // 记录遍历到当前的以最小价格买入 int min_price = prices[0]; for (int i = 1; i < prices.size(); i++) { // 更新收益 profit = max(profit, prices[i] - min_price); // 更新最小买入价格 min_price = min(min_price, prices[i]); } // 返回最大收益 return profit; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解