LeetCode 740: Delete and Earn Solution
Master LeetCode problem 740 (Delete and Earn), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
740. Delete and Earn
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming. We first count the occurrences of each number in the input array. Then, we create two arrays skip and take, where skip[i] represents the maximum points we can get if we skip the i-th element, and take[i] represents the maximum points we can get if we take the i-th element.
We iterate over the values from 0 to the maximum value in the input array, and for each value i, we update the skip and take arrays based on the optimal strategy of taking or skipping the current value.
Finally, the maximum points we can earn is the maximum value between the last elements of skip and take arrays.
Time Complexity: The time complexity of this solution is O(N) where N is the number of elements in the input array.
Space Complexity: The space complexity of this solution is O(N) where N is the number of elements in the input array.
Solution Code
class Solution {
public int deleteAndEarn(int[] nums) {
int maxVal = 0;
for (int num : nums) {
maxVal = Math.max(maxVal, num);
}
int[] count = new int[maxVal + 1];
for (int num : nums) {
count[num]++;
}
int[] skip = new int[maxVal + 1];
int[] take = new int[maxVal + 1];
for (int i = 1; i <= maxVal; i++) {
skip[i] = Math.max(skip[i - 1], take[i - 1]);
take[i] = skip[i - 1] + count[i] * i;
}
return Math.max(skip[maxVal], take[maxVal]);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 740 (Delete and Earn)?
This page provides optimized solutions for LeetCode problem 740 (Delete and Earn) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 740 (Delete and Earn)?
The time complexity for LeetCode 740 (Delete and Earn) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 740 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 740 in Java, C++, or Python.