[LeetCode] Best Time to Buy and Sell Stock
来源:互联网 发布:win7开软件盘 编辑:程序博客网 时间:2024/05/17 02:49
题干:
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
题目解析:
这道题目也是一道动态规划的题目,所求的是利益的最大值,即求某一天买和某一天卖赚取的利润最大值。这里不能使用贪心算法直接找出最大最小值的差值,所以必须先购入后售出,因此这里必须从第一天开始对数组进行扫描,维护两个值,一个是最大利益profit,一个是最小商品价格。第一天的时候,最小商品价格就是第一天的价格,利益为0,而后递增,当当天的利益大于profit时,更新profit的值,同时比较价格,保留最小的价格,这样以O(n)的复杂度即可以找出最大的利益profit。
class Solution {public: int maxProfit(vector<int>& prices) { int size = prices.size(); if (size == 1 || size == 0) return 0; int min_buy = prices[0], profit = 0; for (int i = 1; i < size; i ++) { if (prices[i] - min_buy > profit) { profit = prices[i] - min_buy; } if (prices[i] < min_buy) min_buy = prices[i]; } return profit; }};
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- PHP邮件发送代码实现
- Leetcode 714
- Handler源码原理分析
- Choosing Capital for Treeland (树形dp)
- LeetCode-Split Linked List in Parts
- [LeetCode] Best Time to Buy and Sell Stock
- 为什么java函数不支持参数默认值?
- angular2
- 在列表中找出两个彼此最接近但不相等的数
- 使用Java实现最大堆
- 九、Docker-compose
- Lintcode76 Longest Increasing Subsequence solution 题解
- Okhttp网络请求post方式 加Json解析
- android studio gradle依赖解析