|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 740. Delete and Earn |
| 5 | + * |
| 6 | + * Given an array nums of integers, you can perform operations on the array. |
| 7 | + * In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1. |
| 8 | + * You start with 0 points. Return the maximum number of points you can earn by applying such operations. |
| 9 | +
|
| 10 | + Example 1: |
| 11 | + Input: nums = [3, 4, 2] |
| 12 | + Output: 6 |
| 13 | + Explanation: |
| 14 | + Delete 4 to earn 4 points, consequently 3 is also deleted. |
| 15 | + Then, delete 2 to earn 2 points. 6 total points are earned. |
| 16 | +
|
| 17 | + Example 2: |
| 18 | + Input: nums = [2, 2, 3, 3, 3, 4] |
| 19 | + Output: 9 |
| 20 | + Explanation: |
| 21 | + Delete 3 to earn 3 points, deleting both 2's and the 4. |
| 22 | + Then, delete 3 again to earn 3 points, and 3 again to earn 3 points. |
| 23 | + 9 total points are earned. |
| 24 | +
|
| 25 | + Note: |
| 26 | + The length of nums is at most 20000. |
| 27 | + Each element nums[i] is an integer in the range [1, 10000].*/ |
| 28 | + |
| 29 | +public class _740 { |
| 30 | + public static class Solution1 { |
| 31 | + /** |
| 32 | + * Since the number is within range [1, 10000], we can build another array: |
| 33 | + * each number in the array denotes the total sum of this number that appears in this array |
| 34 | + * and |
| 35 | + * use the numbers themselves in the indices of another array |
| 36 | + * |
| 37 | + * credit: https://leetcode.com/problems/delete-and-earn/discuss/109895/JavaC++-Clean-Code-with-Explanation*/ |
| 38 | + public int deleteAndEarn(int[] nums) { |
| 39 | + int n = 10001; |
| 40 | + int[] values = new int[n]; |
| 41 | + for (int num : nums) { |
| 42 | + values[num] += num; |
| 43 | + } |
| 44 | + |
| 45 | + int take = 0; |
| 46 | + int skip = 0; |
| 47 | + for (int i = 0; i < n; i++) { |
| 48 | + int takeI = skip + values[i]; |
| 49 | + int skipI = Math.max(skip, take); |
| 50 | + take = takeI; |
| 51 | + skip = skipI; |
| 52 | + } |
| 53 | + return Math.max(take, skip); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments