【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),代码很优美。

原创粉丝点击