File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Problem: 2016. Maximum Difference Between Increasing Elements
3+ * Difficulty: Easy
4+ * URL: https://leetcode.com/problems/maximum-difference-between-increasing-elements/
5+ *
6+ * Approach:
7+ * - Use two pointers (left, right).
8+ * - Keep track of the minimum element seen so far at `left`.
9+ * - For each `right`, calculate difference with `left`.
10+ * - Update maximum difference if current difference is larger.
11+ * - If `nums[right]` is smaller or equal, move `left` to `right`.
12+ *
13+ * Time Complexity: O(n)
14+ * Space Complexity: O(1)
15+ */
16+
17+ class Solution {
18+ public int maximumDifference (int [] nums ) {
19+ int max = -1 ;
20+ int left = 0 ;
21+ int right = 1 ;
22+
23+ while (right < nums .length && left < nums .length ) {
24+ if (nums [left ] < nums [right ]) {
25+ int diff = nums [right ] - nums [left ];
26+ max = Math .max (max , diff );
27+ } else {
28+ left = right ; // move left to the new minimum
29+ }
30+ right ++;
31+ }
32+
33+ return max ;
34+ }
35+ }
36+
37+ // Another solution
38+
39+ class Solution {
40+ public int maximumDifference (int [] nums ) {
41+ int min = nums [0 ];
42+ int max = -1 ;
43+ for (int i =0 ; i <nums .length ; i ++){
44+ min = Math .min (min , nums [i ]);
45+ if (min <nums [i ]){
46+ max =Math .max (max , nums [i ]-min );
47+ }
48+ }
49+ return max ;
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments