Contest: https://leetcode.com/contest/weekly-contest-392/
Q1 Longest Strictly Increasing or Strictly Decreasing Subarray
Description: https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray/description/
Approach: Brute force
Code:
class Solution { public int longestMonotonicSubarray(int[] nums) { if (nums.length == 1) return 1; int inc = 0, dec = 0, countInc = 0, countDec = 0; int j; for (int i = 0; i < nums.length-1; i++) { countInc = 1; countDec = 1; for (j=i+1; j<nums.length;j++) if (nums[j] > nums[j-1]) countInc++;else break; if (countInc > inc) inc = countInc; for (j=i+1; j<nums.length;j++) if (nums[j] < nums[j-1]) countDec++;else break; if (countDec > dec) dec = countDec; } return Math.max(inc,dec); } }
Q2 Lexicographically Smallest String After Operations With Constraint
Description: https://leetcode.com/problems/lexicographically-smallest-string-after-operations-with-constraint/description/
Approach: Greedy.
Code:
class Solution { public String getSmallestString(String s, int k) { if (k == 0) return s; char x ; int diff; StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { if (k==0) { sb.append(c); } else { x = 'a'; diff = Math.min( Math.abs(x-c), (x-c +26) %26); while (diff > k) { x++; diff = Math.min( Math.abs(x-c), (x-c +26) %26); } sb.append(x); k = k - diff; } } return sb.toString(); } }
Q3 Minimum Operations to Make Median of Array Equal to K
Description: https://leetcode.com/problems/minimum-operations-to-make-median-of-array-equal-to-k/
Code:
class Solution { public long minOperationsToMakeMedianK(int[] nums, int k) { Arrays.sort(nums); int median = nums[nums.length / 2]; long operations = 0; if (k > median) { for (int i = nums.length / 2; i < nums.length; i++) { operations += nums[i] < k ? k - nums[i] : 0; } } else { for (int i = 0; i <= nums.length / 2; i++) { operations += nums[i] > k ? nums[i] - k : 0; } } return operations; } }
Q4 Minimum Cost Walk in Weighted Graph
Description: https://leetcode.com/problems/minimum-cost-walk-in-weighted-graph/description/
Code: