leetcode 121
来源:互联网 发布:金石造价软件下载 编辑:程序博客网 时间:2024/06/06 16:59
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: 5max. 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: 0In this case, no transaction is done, i.e. max profit = 0.
Subscribe to see which companies asked this question.
可能类似的题做的多了?
思路:sum[i]为a~i 最大值
sum[i+1] = max{0, sum[i]-price[i]+price[i+1]}
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
if(size == 0)
return 0;
int rel[size] = {0};
for(int i = 1; i < size ; i ++)
{
rel[i] = rel[i - 1] - prices[i - 1] + prices[i];
if (rel[i] < 0)
rel[i] = 0;
}
int max = 0;
for(int i = 1; i < size ; i ++)
{
if (rel[i] > max)
max = rel[i];
}
return max;
}
};
- leetcode-121
- leetcode 121
- leetcode 121
- leetcode-121
- Leetcode 121
- leetcode #121 in cpp
- leetCode练习(121)
- [Leetcode] 121, 122, 3
- week14-leetcode #121-BestTimetoBuyandSellStock
- leetcode 121 309
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- 大数据IMF传奇行动绝密课程第92课:SparkStreaming中Transformations和状态管理解密
- 2017/4/3 csp-Markdown
- 返回数组中的小数组的最大值
- visio粘贴到word中只显示一部分
- CSDN博客自定义栏目——Google、百度、必应站内搜索框
- leetcode 121
- 全排列
- 如何在官网上下载可安装版的MySQL数据库
- java的File类
- Spring MVC @ModelAttribute 使用
- 冒泡排序的步骤
- Lintcode 下一个排列
- OpenCV 中图像的算术运算、平滑处理、阈值化及图像金字塔
- 大数据IMF传奇行动绝密课程第93课:SparkStreaming updateStateByKey案例实战和内置源码解密