Line data Source code
1 : // Copyright (c) 2025 The Authors. All rights reserved.
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // https://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 :
15 : // Authors: liubang (it.liubang@gmail.com)
16 : // Created: 2025/06/17 00:07
17 :
18 : #include <climits>
19 : #include <vector>
20 :
21 : #include <gtest/gtest.h>
22 :
23 : namespace {
24 : class Solution {
25 : public:
26 4 : int maximumDifference(const std::vector<int>& nums) {
27 4 : int minidx = 0;
28 4 : int max = INT_MIN;
29 112 : for (int i = 0; i < nums.size() - 1; ++i) {
30 108 : if (nums[minidx] > nums[i]) {
31 96 : minidx = i;
32 : }
33 108 : max = std::max(max, nums[i + 1] - nums[minidx]);
34 : }
35 4 : return max <= 0 ? -1 : max;
36 : }
37 : };
38 : } // namespace
39 :
40 4 : TEST(Leetcode, maximum_difference_between_increasing_elements) {
41 1 : Solution s;
42 1 : EXPECT_EQ(4, s.maximumDifference({7, 1, 5, 4}));
43 1 : EXPECT_EQ(-1, s.maximumDifference({9, 4, 3, 2}));
44 1 : EXPECT_EQ(9, s.maximumDifference({1, 5, 2, 10}));
45 1 : EXPECT_EQ(-1, s.maximumDifference(
46 : {999, 997, 980, 976, 948, 940, 938, 928, 924, 917, 907, 907, 881, 878, 864,
47 : 862, 859, 857, 848, 840, 824, 824, 824, 805, 802, 798, 788, 777, 775, 766,
48 : 755, 748, 735, 732, 727, 705, 700, 697, 693, 679, 676, 644, 634, 624, 599,
49 : 596, 588, 583, 562, 558, 553, 539, 537, 536, 509, 491, 485, 483, 454, 449,
50 : 438, 425, 403, 368, 345, 327, 287, 285, 270, 263, 255, 248, 235, 234, 224,
51 : 221, 201, 189, 187, 183, 179, 168, 155, 153, 150, 144, 107, 102, 102, 87,
52 1 : 80, 57, 55, 49, 48, 45, 26, 26, 23, 15}));
53 1 : }
|