Just use a greedy algorithm; while iterating through the array nums:
if the current value is larget than the smallest value seen so far, update the
ansifnums[i] - mnis greaterelse, update
mnto benums[i]
code
class Solution {
public:
int maximumDifference(vector<int>& nums) {
int ans = -1;
int mn = nums[0];
for (int i = 1; i < nums.size(); ++i) {
if (mn < nums[i]) {
ans = max(ans, nums[i]-mn);
} else {
mn = nums[i];
}
}
return ans;
}
};
complexity
- Time:
O(n)wherenis the size ofnums- Space:
O(1)
time taken
- 2 minutes and 28 seconds