|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.Collections; |
| 6 | +import java.util.List; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +/** |
| 10 | + * 1243. Array Transformation |
| 11 | + * |
| 12 | + * Given an initial array arr, every day you produce a new array using the array of the previous day. |
| 13 | + * |
| 14 | + * On the i-th day, you do the following operations on the array of day i-1 to produce the array of day i: |
| 15 | + * |
| 16 | + * If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented. |
| 17 | + * If an element is bigger than both its left neighbor and its right neighbor, then this element is decremented. |
| 18 | + * The first and last elements never change. |
| 19 | + * After some days, the array does not change. Return that final array. |
| 20 | + * |
| 21 | + * Example 1: |
| 22 | + * Input: arr = [6,2,3,4] |
| 23 | + * Output: [6,3,3,4] |
| 24 | + * Explanation: |
| 25 | + * On the first day, the array is changed from [6,2,3,4] to [6,3,3,4]. |
| 26 | + * No more operations can be done to this array. |
| 27 | + * |
| 28 | + * Example 2: |
| 29 | + * Input: arr = [1,6,3,4,3,5] |
| 30 | + * Output: [1,4,4,4,4,5] |
| 31 | + * Explanation: |
| 32 | + * On the first day, the array is changed from [1,6,3,4,3,5] to [1,5,4,3,4,5]. |
| 33 | + * On the second day, the array is changed from [1,5,4,3,4,5] to [1,4,4,4,4,5]. |
| 34 | + * No more operations can be done to this array. |
| 35 | + * |
| 36 | + * Constraints: |
| 37 | + * 1 <= arr.length <= 100 |
| 38 | + * 1 <= arr[i] <= 100 |
| 39 | + * */ |
| 40 | +public class _1234 { |
| 41 | + public static class Solution1 { |
| 42 | + public List<Integer> transformArray(int[] arr) { |
| 43 | + int[] copy; |
| 44 | + do { |
| 45 | + copy = Arrays.copyOf(arr, arr.length); |
| 46 | + for (int i = 1; i < arr.length - 1; i++) { |
| 47 | + if (copy[i] < copy[i - 1] && copy[i] < copy[i + 1]) { |
| 48 | + arr[i]++; |
| 49 | + } else if (copy[i] > copy[i - 1] && copy[i] > copy[i + 1]) { |
| 50 | + arr[i]--; |
| 51 | + } |
| 52 | + } |
| 53 | + } while (!Arrays.equals(copy, arr)); |
| 54 | + return Arrays.stream(arr) |
| 55 | + .boxed() |
| 56 | + .collect(Collectors.toList()); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments