63 股票的最大利润
题目
求买卖股票一次能获得的最大利润。例如,输入{9,11,8,5,7,12,16,14},5的时候买入,16的时候卖出,则能获得最大利润11。
C 语言题解
遍历过程中记录最小值min,然后计算当前值与min的差值diff,并更新maxDiff。
int MaxDiff(const int* numbers, unsigned length)
{
if (numbers == nullptr && length < 2)
return 0;
// 假设第一个数是最小值
int min = numbers[0];
int maxDiff = numbers[1] - min;
for (int i = 2; i < length; ++i)
{
if (numbers[i - 1] < min)
min = numbers[i - 1];
int currentDiff = numbers[i] - min;
if (currentDiff > maxDiff)
maxDiff = currentDiff;
}
return maxDiff;
}
C++ 题解
class Solution {
public:
int maxDiff(vector<int>& nums) {
if(nums.size()==0) return 0;
int buy=nums[0],diff=0;
for(auto &x:nums){
if(x<buy) buy=x;
if(x-buy>diff) diff=x-buy;
}
return diff;
}
};
python 题解
class Solution(object):
def maxDiff(self, nums):
if not nums:
return 0
min_ = nums[0]
max_ = 0
for i in nums:
min_ = min(min_,i)
max_ = max(max_,i - min_)
return max_