【题目描述】
注意这题与之前的 AcWing 1055. 股票买卖 II 有个不太一样的地方,就是这里只允许买卖一次。也就要求差距最大的两个点。
暴力做法
【思路】
双层循环枚举i时买进 j时抛出
class Solution {
public int maxDiff(int[] nums) {
int n = nums.length;
int ans = 0;
//i时买进 j时抛出
for(int i = 0; i < n - 1; i ++)
for(int j = i + 1; j < n; j ++){
ans = Math.max(ans, nums[j] - nums[i]);
}
return ans;
}
}
贪心
【思路】
枚举每一个抛出日子,因为买入日子一定在卖出日子之前,为了获利最多,买入的日子的股票价格应该尽可能低。
class Solution {
public int maxDiff(int[] nums) {
int n = nums.length;
if( n == 0) return 0;
int ans = 0;
int min = nums[0];//假设第0天买进的时候价格最低
//枚举每一个抛出日子,买入日子一定在卖出日子之前,为了获利最多,买入的日子的股票价格应该尽可能低
for(int j = 1; j < n; j ++){
if( nums[j] < min){
min = nums[j];
continue;
}
if( nums[j] - min > ans) ans = nums[j] - min;
}
return ans;
}
}
class Solution {
public int maxDiff(int[] nums) {
/**
枚举每一个抛出的日子,买入的日子一定在抛出之前,尽可能地选择那些股价更低的日子买进
**/
int n = nums.length;
if (n == 0) return 0;
// 用一个变量min来维护前j天的最小值 省去一层for循环
int min = nums[0];
int ans = 0;
for (int j = 0; j < n; j ++) {
// 更新前j天的最小值
if (min > nums[j]) {
min = nums[j];
continue;
}
if (nums[j] - min > ans) ans = nums[j] - min;
}
return ans;
}
}