1. 题目

1.1 英文题目

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

1.2 中文题目

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

1.3输入输出

输入 输出
prices = [7,1,5,3,6,4] 5
prices = [7,6,4,3,1] 0

1.4 约束条件

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

2. 实验平台

IDE:VS2019

IDE版本:16.10.1

语言:c++11

3. 分析

这一题最简单粗暴的方法就是穷举枚举,代码为:

class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxprofit = 0;
for (int i = 0; i < prices.size() - 1; i++)
{
for (int j = i + 1; j < prices.size(); j++)
{
int temp = prices[j] - prices[i];
if ( temp > maxprofit)
{
maxprofit = temp;
}
}
}
return maxprofit;
}
};

这样做只适用于数据较少的情形,而对于大数据很容易造成超时现象,那么能不能进行优化一下,我想到了双指针法,快指针负责遍历整个数组,当快指针的值小于等于慢指针的值时,将慢指针指向快指针指向的位置。新代码如下:

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> ans;
for(int i = 0; i < rowIndex + 1; i++)
{
vector<int> temp(i + 1);
temp[0] = temp[i] = 1;
for(int j = 1; j < i; j++)
{
temp[j] = ans[j - 1] + ans[j];
}
ans = temp;
}
return ans;
}
};

但是我们提交后发现算法时间和空间复杂度都没变,于是我在想还有没有优化空间,我发现每行计算时都需要重新定义temp,并为其开辟内存空间,有待优化,故可以将其提前定义,并在每行计算时重定义temp大小,代码如下:

class Solution {
public:
int maxProfit(vector<int>& prices) {
int slow = 0;
int max = 0;
int temp = 0;
for (int quick = 1; quick < prices.size(); quick++)
{
temp = prices[quick] - prices[slow];
if (temp <= 0) slow = quick;
else if (temp > max) max = temp;
}
return max;
}
};

这次性能不错。在写这段程序的过程中,我最开始是将temp在for循环内进行定义并赋值,但是我发现如果把它放在外面定义,可以优化算法的时间和空间复杂度,于是我想到,变量的定义也是需要消耗时间和空间的,因此最好是提前定义好,也就是尽量减少定义次数。

另外,在题目的solution中我还发现大佬用Kadane's Algorithm进行求解。他的大概思想就是将数组中相邻元素的差值(后减去前)重新组成一个数组,之后对这个求最大子序列和,详细介绍可以参考:https://blog.csdn.net/shendezhuti/article/details/105114569

代码如下:

class Solution {
public int maxProfit(int[] prices) {
int maxCur = 0, maxSoFar = 0;
for(int i = 1; i < prices.length; i++) {
maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);
maxSoFar = Math.max(maxCur, maxSoFar);
}
return maxSoFar;
}
};

Leetcode No.121 Best Time to Buy and Sell Stock(c++实现)的更多相关文章

  1. 【刷题-LeetCode】121 Best Time to Buy and Sell Stock

    Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a gi ...

  2. 【一天一道LeetCode】#121. Best Time to Buy and Sell Stock

    # 一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Say ...

  3. 【LeetCode】121. Best Time to Buy and Sell Stock 解题报告(Java & Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 C++ 解法 日期 ...

  4. LeetCode OJ 121. 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 day i. If you were ...

  5. 【leetcode】121. Best Time to Buy and Sell Stock(股票问题)

    You are given an array prices where prices[i] is the price of a given stock on the ith day. You want ...

  6. 【一天一道LeetCode】#122. Best Time to Buy and Sell Stock II

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Say you ...

  7. 121. Best Time to Buy and Sell Stock (一) leetcode解题笔记

    121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of ...

  8. 30. leetcode 121. Best Time to Buy and Sell Stock

    121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of ...

  9. leetcode 121. Best Time to Buy and Sell Stock 、122.Best Time to Buy and Sell Stock II 、309. Best Time to Buy and Sell Stock with Cooldown

    121. Best Time to Buy and Sell Stock 题目的要求是只买卖一次,买的价格越低,卖的价格越高,肯定收益就越大 遍历整个数组,维护一个当前位置之前最低的买入价格,然后每次 ...

随机推荐

  1. python 中的变量内存以及关于is ==、 堆栈、

    在工作学习中会碰到一些python中变量与内存层面的问题理解,虽然是在不断的解决,但是并没有做过这方面的总结. 变量:用来标识(identify)一块内存区域.为了方便表示内存,我们操作变量实质上是在 ...

  2. 4.3 Python3进阶-函数嵌套和嵌套调用

    >>返回主目录 源码 # 函数嵌套 def func1(): print("这是外部函数") def func2(): print("这是内部函数1" ...

  3. 行者APP适配国外环境问题解决

    (本文1151字,阅读约5分钟) 玩骑行的同伴都知道,长途骑行,第一需要好的硬件,如大腿发动机.车子.装备等:二是需要好的软件,如意志.有氧能力.骑行app等. 到雅加达后,才发现在国内用了几年的黑鸟 ...

  4. Selenium八种元素定位方法源码阅读

    接触过Selenium的都知道元素定位有八种方法,但用不同的方法在执行时有什么区别呢? 元素定位8种方法(Python版),当然还有每一个方法对应的find_elements方法 find_eleme ...

  5. C# HTTP请求对外接口、第三方接口公用类

    /// <summary> /// 网络数据请求公共函数 /// </summary> public class HttpWebRequestCommon { #region ...

  6. 固态LiDAR,半固态混合LiDAR,机械LiDAR

    固态LiDAR,半固态混合LiDAR,机械LiDAR 1. APD/SPAD 2轴MEMS扫描镜+ SPAD图像传感器在混合固态LiDAR中的应用 APD的工作模式分为线性模式和盖革模式两种.当APD ...

  7. AI推理单元

    AI推理单元 推理服务供了一套面向 MLU(Machine Learning Unit,机器学习单元)设备的类似服务器的推理接口(C++11标准),以及模型加载与管理,推理任务调度等功能,极大地简化了 ...

  8. Dockerfile构建实践

    Dockerfile构建实践 本文介绍了用于构建有效图像的推荐最佳实践和方法. Docker通过从一个Dockerfile文本文件中读取指令来自动构建映像,该文本文件按顺序包含构建给定映像所需的所有命 ...

  9. Pass Infrastructure基础架构(下)

    Pass Infrastructure基础架构(下) pass注册  PassRegistration该类在示例中简要显示了各种pass类型的定义 .该机制允许注册pass类,以便可以在文本pass管 ...

  10. GPU上创建目标检测Pipeline管道

    GPU上创建目标检测Pipeline管道 Creating an Object Detection Pipeline for GPUs 今年3月早些时候,展示了retinanet示例,这是一个开源示例 ...