LeetCode:Best Time to Buy and Sell Stock
来源:互联网 发布:匡恩网络 知乎 编辑:程序博客网 时间:2024/06/03 22:52
题目描述: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.
中文意思:给定一个序列,找出最大差值(只允许后面数减去前面数),没有的话则为0
方法1:两层循环,直接对prices[j] - prices[i] (j > i, i = 0, 1, ..., pricesSize - 2)进行枚举,时间代价为O(n^2)
方法2:动态规划,转移方程为profit[i] = max(profit[i-1], prices[i] - min_price)。也就是说到第i项的时候,最大的利润要么为第i-1项获得的最大利润(意味着第i项不值得交换),要么为把第i项交换掉,用前面最小的值。
方法2的代码(空间代价可以为常数,自己可以尝试下):
int maxProfit(int* prices, int pricesSize) { int* profit = (int*)malloc(pricesSize * sizeof(int)); memset(profit, 0, pricesSize * sizeof(int)); int min_price = prices[0]; for (int i = 1; i < pricesSize; ++i) { if (profit[i - 1] > prices[i] - min_price) { profit[i] = profit[i - 1]; } else { profit[i] = prices[i] - min_price; } if (prices[i] < min_price) { min_price = prices[i]; } } int max_profit = 0; for (int i = 0; i < pricesSize; ++i) { if (max_profit < profit[i]) { max_profit = profit[i]; } } return max_profit;}
1 0
- 【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
- 稀疏矩阵的压缩存储和逆置,以及快速逆置,以及稀疏矩阵的加法
- HDU 1667 百练 1288 POJ 2286
- 2016ACM暑假集训 - 4 Values whose Sum is 0
- 版本控制(link)
- CodeForces 604AUncowed Forces (模拟 oj 评分)
- LeetCode:Best Time to Buy and Sell Stock
- openjudge 1.6 08:石头剪刀布
- 输出菱形,空心菱形
- Codeforces Round #362 (Div. 2)C. Lorenzo Von Matterhorn 二叉树结点规律
- Labview通过RS422通讯接口PC与下位机通信
- java中选择排序,冒泡排序和二分法查找学习记录
- Servlet---文件上传/打散目录/进度条
- 内核打印杂谈
- JHTP小结_第十一章_深入理解异常(Exception Handling)