您的位置:首页 > 其它

求数组元素最大差值

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: