【C++】数组中后前差值最大的值
来源:互联网 发布:在淘宝上怎样发链接 编辑:程序博客网 时间:2024/06/08 03:53
LeetCode 121Best 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 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.
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)
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
说白了就一句话:找出数组中后一个数比前一个数的差值大的值。
自己写了一种方法:
//定义一个temp数组用于保存到当前位置的最小值。int findMaxDiff(vector<int>& nums){ if(nums.size()==0) return 0; vector<int> temps(nums.size(),0); temps[0]=nums[0]; int i; //获取每个位置的最小值 for(i=1;i<nums.size();++i){ if(nums[i]<temps[i-1]) temps[i]=nums[i]; else temps[i]=temps[i-1]; } int diff=0,t=0; for(i=1;i<nums.size();++i){ if(nums[i]>temps[i-1]) t=nums[i]-temps[i-1]; if(t>diff) diff=t; } return diff;}
先求最小值数组,然后再求差值最大的数。这个算法有臃肿,空间复杂度O(n).
优化:上面的空间复杂度可以再优化一下;
若当前值小于minDF则赋值过去,而diff等于当前值减去minDF的最小值
int findMaxDiff2(vector<int>& nums){ int diff = 0, minDF = INT_MAX; for(int i=0;i<nums.size();++i){ if(nums[i]<minDF) minDF=nums[i]; else{ if(nums[i]-minDF>diff) diff = nums[i]-minDF; } } return diff;}
空间复杂度O(1),代码很优美。
阅读全文
0 0
- 【C++】数组中后前差值最大的值
- 数组元素的最大差值
- 无序数组的相邻最大差值
- 数组中最大的差值-LintCode
- 数组中的最大差值
- 返回数组最大差值
- c++-相邻最大差值
- 数组中找最大差值
- 求数组元素最大差值
- 数组左边减去右边数值的最大差值
- 【面试】求数组元素最大差值的问题
- 【面试】求数组元素最大差值的问题
- 数组左边减去右边数值的最大差值
- 求一个数组中两个元素的最大差值
- 数组左边减去右边数值的最大差值
- 求数组排序后相邻数的最大差值
- 二维数组的行列求和以及最大差值
- 求数组排序后相邻两个数的最大差值
- redis操作基本命令 转载自用
- sql语句导出pdm模型生成docx文档
- QT
- 各种问题解决方案总结【记录】(持续更新)
- Android策略模式学习笔记
- 【C++】数组中后前差值最大的值
- 网易、阿里巴巴等互联网大佬也钟情于数据可视化解决方案
- zookeeper的四种类型的节点
- HTTP状态码知道哪些?
- fabric配置详解
- zabbix安装部署二
- OpenStack容器化之路:Kolla项目介绍
- SpringMVC 文件上传配置,多文件上传,使用的MultipartFile的实例
- Mac 查看端口被占用&删除进程