LeetCode-Best Time to Buy and Sell Stock-解题报告
来源:互联网 发布:图片加字软件 编辑:程序博客网 时间:2024/05/03 08:42
原题链接https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Say you have an array for which the ith element is the price of a given stock on dayi.
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.
给你一个数组,nums[i]表示第i的股价,最多交易一次,问作大利益是多少。
很简单,求出用 p[i]表示第i天与前一天的股票价格差,所以p[i] = nums[i] - nums[i-1],p[i] + p[i-1] = nums[i] - nums[i-2],所以将题目转化成了最大子段和的问题。为了节省空间,我将他们的差保存在了给定的数组nums中,nums[i-1]表示第i天与i-1天的股票差。
复杂度为o(n)
<pre name="code" class="cpp">class Solution {public: int maxProfit(vector<int>& prices) { if (prices.size() < 2)return 0;for (int i = 1; i < prices.size(); ++i) prices[i - 1] = prices[i] - prices[i - 1]; int ans = -1, tmp = 0; for (int i = 0; i < prices.size() - 1; ++i) { if (tmp > ans) ans = tmp; if (tmp >= 0)tmp += prices[i]; else tmp = 0, tmp += prices[i];} if (tmp >ans) ans = tmp; return ans; }};
0 0
- LeetCode-Best Time to Buy and Sell Stock-解题报告
- 【LeetCode】Best Time to Buy and Sell Stock 解题报告
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- 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 IV -解题报告
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- [leetcode] 121. Best Time to Buy and Sell Stock 解题报告
- [leetcode] 123. Best Time to Buy and Sell Stock III 解题报告
- [leetcode] 122. Best Time to Buy and Sell Stock II 解题报告
- [leetcode] 309. Best Time to Buy and Sell Stock with Cooldown 解题报告
- [leetcode] 188. Best Time to Buy and Sell Stock IV 解题报告
- leetcode 309. Best Time to Buy and Sell Stock with Cooldown 解题报告
- LeetCode 122. Best Time to Buy and Sell Stock II 解题报告
- Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告
- Leetcode 122. Best Time to Buy and Sell Stock II 股票买卖2 解题报告
- Leetcode 123. Best Time to Buy and Sell Stock III 股票买卖3 解题报告
- LeetCode解题报告 309. Best Time to Buy and Sell Stock with Cooldown[medium]
- ui-grid的笔记
- 8天学通MongoDB——第八天 驱动实践
- CScrollView双缓冲绘图
- sina微博开放平台中使用OAuth验证并发表微博
- 视差滚动
- LeetCode-Best Time to Buy and Sell Stock-解题报告
- Yin ~ Regularized Minimization method
- [leetcode] 114.Flatten Binary Tree to Linked List
- RTP 头格式
- Window下Ghost博客开发环境的搭建
- C#获取上个月第一天和最后一天日期的方法
- android webview中调用了js的时候混淆注意事项
- windows下如何安装pip
- iOS开发 调试 网络限速