求数组元素最大差值
2014-11-21 06:13
246 查看
一、问题描述:
如果一个人在知道了股票每天的股价以后,对该股票进行投资,问什么时候买入和卖出(注意这里有先后顺序)能取得最大的收益。其数学模型就是,给定一个整数数组,a[1],a[2],...,a,每一个元素a[i]可以和它左边(a[i-1],a[i-2],...,a[0])元素做差,求这个数组中最大的差值。
解法:
对于任意a[i]你肯定在遍历到a[i]时,你肯定能拿到a[i]之前的最小数(这个用一个变量保存),那么寻找最大差值就是a[i]与当前最小数的差值中的最大值(用一个变量存储,记为R)。遍历结束后,R即为所求最大差值(对应的位置肯定知道了)。二. 类似问题:
Given an array arr[] of integers, find out the difference between any two elements such that larger element appears after the smaller number in arr[].Examples: If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2). If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9)
我自己想的解法:
#include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; #include <string.h> float maxDiff(float arr[], int n) { int j=0; float max_ = 0; for(int i=1; i<n; i++) { if(arr[j]<arr[i]) max_ = max(max_, arr[i]-arr[j]); else j=i; } return max_; } int main () { float arr[5] = {1,3,2,5,4}; cout<<maxDiff(arr, 5);
相关文章推荐
- 求一个数组中两个元素的最大差值
- 一个无序实数数组中的相邻两个元素的最大差值
- 【编程习题★★★☆☆】寻找数组中元素间最大差值
- 数据结构之——找到无序数组中排序后相邻元素差值的最大值
- 【面试】求数组元素最大差值的问题
- 无序数组求相邻元素最大差值(tiger基金的笔试题)
- 求数组相邻元素差值的最大值快速算法(C++版)
- 【面试】求数组元素最大差值的问题
- 求一个数组中满足一定条件的两个元素的最大差值
- 用递规与分治策略,找出数组中最大元素的位置
- 数组最大差值问题
- 【100题】第三题(数组(元素可为正数、负数、0)的最大子序列和)
- 操作数组的常用方式一----获取数组元素中最大值和最小值
- 操作数组的常用方式一----获取数组元素中最大值和最小值
- 求一个数组中最大的相邻元素之和
- 两算法:求数组元素出现次数和求子数组最大和
- 数组中找出第二个最大的元素(第k大的元素)
- 每天学习一算法系列(5)(已知两个数组,数组里的元素有正有负,但是都是按照从小到大已经排好序,要求用尽可能小的时间复杂度编写一算法求出两个数组的最大交集)
- n个元素的数组中找出前K个最大数最有效算法O(nlg(k))
- 5-8: 输入一个5行、6列的数组,找出该数组中绝对值最大的元素,输出该元素及其两个下标值