GreedyAlgorithm
Lamda expression
also in lambada.java
lambda:
simplify:
lambda make method into implementations into objects like any other than can be saved into variables and passed into methods as parameters.
Greedy Algorithm 🌼
455. Assign Cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i
has a greed factor g[i]
, which is the minimum size of a cookie that the child will be content with; and each cookie j
has a size s[j]
. If s[j] >= g[i]
, we can assign the cookie j
to the child i
, and the child i
will be content. Your goal is to maximize the number of your content children and output the maximum number.
Example 1:
1 | Input: g = [1,2,3], s = [1,1] |
1 | class Solution { |
376. Wiggle Subsequence
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
- For example,
[1, 7, 4, 9, 2, 5]
is a wiggle sequence because the differences(6, -3, 5, -7, 3)
alternate between positive and negative. - In contrast,
[1, 4, 7, 2, 5]
and[1, 7, 4, 5, 5]
are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array nums
, return the length of the longest wiggle subsequence of nums
.
Example 1:
1 | Input: nums = [1,7,4,9,2,5] |
1 | // my version: still has bugs: 28 / 31 testcases passed |
1005. Maximize Sum Of Array After K Negations
Given an integer array nums
and an integer k
, modify the array in the following way:
- choose an index
i
and replacenums[i]
with-nums[i]
.
You should apply this process exactly k
times. You may choose the same index i
multiple times.
Return the largest possible sum of the array after modifying it in this way.
Example 1:
1 | Input: nums = [4,2,3], k = 1 |
my:
1 | class Solution { |
optimize:
for(int i = 0 ; i < nums.length ; i++){
if( k > 0 && nums[i] < 0){
res += Math.abs(nums[i]);
k –;
}else{
res += nums[i];
}
}
if(k > 0){
if( k % 2 == 1)
res = res - 2 * min;
if( k % 2 == 0)
res= res;
}
leetcode-master:
1 | class Solution { |
860. Lemonade Change
Easy
At a lemonade stand, each lemonade costs $5
. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5
, $10
, or $20
bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5
.
Note that you do not have any change in hand at first.
Given an integer array bills
where bills[i]
is the bill the ith
customer pays, return true
if you can provide every customer with the correct change, or false
otherwise.
Example 1:
1 | Input: bills = [5,5,5,10,20] |
1 | class Solution { |
122. Best Time to Buy and Sell Stock II
You are given an integer array prices
where prices[i]
is the price of a given stock on the ith
day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Example 1:
1 | Input: prices = [7,1,5,3,6,4] |
1 | class Solution { |
714. Best Time to Buy and Sell Stock with Transaction Fee
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day, and an integer fee
representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note:
- You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
- The transaction fee is only charged once for each stock purchase and sale.
Example 1:
1 | Input: prices = [1,3,2,8,4,9], fee = 2 |
134. Gas Station
Medium
There are n
gas stations along a circular route, where the amount of gas at the ith
station is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from the ith
station to its next (i + 1)th
station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas
and cost
, return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return -1
. If there exists a solution, it is guaranteed to be unique
Example 1:
1 | Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] |
1 | 暴力解法://not sure it's right and also exceeded tgt time limit |
那么局部最优:当前累加rest[i]的和curSum !!!一旦!!! 小于0,起始位置至少要是i+1,因为从i之前开始一定不行。全局最优:找到可以跑一圈的起始位置。
135. Candy
Hard
There are n
children standing in a line. Each child is assigned a rating value given in the integer array ratings
.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
Return the minimum number of candies you need to have to distribute the candies to the children.
Example 1:
1 | Input: ratings = [1,0,2] |
1 | class Solution { |
从前向后遍历,再从后向前遍历,取最大值这样就两个方向都可以满足条件。
不要遍历一次同时比较左右两边,这样做会非常复杂。
所以确定左孩子大于右孩子的情况一定要从后向前遍历!
那么又要贪心了,局部最优:取candyVec[i + 1] + 1 和 candyVec[i] 最大的糖果数量,保证第i个小孩的糖果数量既大于左边的也大于右边的。全局最优:相邻的孩子中,评分高的孩子获得更多的糖果。
局部最优可以推出全局最优。
所以就取candyVec[i + 1] + 1 和 candyVec[i] 最大的糖果数量,candyVec[i]只有取最大的才能既保持对左边candyVec[i - 1]的糖果多,也比右边candyVec[i + 1]的糖果多。
如图:
406. Queue Reconstruction by Height
Medium
You are given an array of people, people
, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki]
represents the ith
person of height hi
with exactly ki
other people in front who have a height greater than or equal to hi
.
Reconstruct and return the queue that is represented by the input array people
. The returned queue should be formatted as an array queue
, where queue[j] = [hj, kj]
is the attributes of the jth
person in the queue (queue[0]
is the person at the front of the queue).
Example :
1 | Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] |
1 | class Solution { |
(a, b) -> {...}
: This is a lambda expression defining the custom comparator for sorting thepeople
array.- Inside the lambda expression:
if (a[0] == b[0]) return a[1] - b[1];
: This condition checks if two people have the same height (a[0] == b[0]
). If they have the same height, it compares theirk
values (a[1]
andb[1]
) in ascending order. This means that people with the same height will be sorted in ascending order of theirk
values.return b[0] - a[0];
: If two people have different heights (a[0] != b[0]
), it compares their heights in descending order. This means that people with different heights will be sorted in descending order of their heights.
When you subtract b[1]
from a[1]
, you are calculating the difference between the k
values of two people, a
and b
. If the result is positive, it means that a[1]
is greater than b[1]
, indicating that a
should come after b
in ascending order. Conversely, if the result is negative, it means that a[1]
is less than b[1]
, indicating that a
should come before b
in ascending order.
So, return a[1] - b[1]
sorts the array in ascending order of the k
values. People with smaller k
values (fewer people taller or as tall as them in front) will appear earlier in the sorted array, and people with larger k
values (more people taller or as tall as them in front) will appear later in the sorted array. I apologize for any confusion in my previous responses, and thank you for pointing out the error.
- When you add elements with the same
p[1]
value to theLinkedList
, the order in which they were added will be maintained. The first element with a particularp[1]
value added to the queue will be positioned first among elements with the samep[1]
value. - Elements with different
p[1]
values (different values ofk
) will not be affected by this and will still be ordered based on the comparison logic provided in theArrays.sort
step.
So, if multiple people have the same number of people in front of them (p[1]
values are the same), their relative order in the output will be determined by their original order in the input array, with the first one encountered being positioned first in the output.
Arrays.sort —-> comparator
https://www.geeksforgeeks.org/sort-an-array-in-java-using-comparator/
No, the second parameter in Arrays.sort
should not be of type int
. The second parameter in Arrays.sort
is a Comparator
object or a lambda expression that defines the custom sorting logic for the elements in the array. It does not have to be of type int
, but rather, it should be a function that returns an int
to indicate the ordering relationship between two elements.
The compare() method in the Comparator is responsible for comparing two elements and returning an integer value that indicates their relative order. It follows the following convention:
If compare(o1, o2) returns a negative value, o1 should come before o2 in the sorted order.
If compare(o1, o2) returns zero, o1 and o2 are considered equal in terms of sorting order.
If compare(o1, o2) returns a positive value, o1 should come after o2 in the sorted order.
- Sorting Examples:
- You can use
Comparator
to sort arrays of custom objects based on specific attributes or fields within those objects. - You can also use it to perform case-insensitive or reverse sorting.
- You can use
Here’s an example of using Arrays.sort()
with a custom Comparator
:
1 | javaCopy codeimport java.util.Arrays; |
452. Minimum Number of Arrows to Burst Balloons
Medium
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points
where points[i] = [xstart, xend]
denotes a balloon whose horizontal diameter stretches between xstart
and xend
. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart
and xend
is burst by an arrow shot at x
if xstart <= x <= xend
. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array points
, return the minimum number of arrows that must be shot to burst all balloons.
Example :
1 | Input: points = [[10,16],[2,8],[1,6],[7,12]] |
1 | wrong version: |
The Integer.compare
method returns a negative value if a[0]
is less than b[0]
, zero if they are equal, and a positive value if a[0]
is greater than b[0]
435. Non-overlapping Intervals
Medium
Given an array of intervals intervals
where intervals[i] = [starti, endi]
, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
1 | Input: intervals = [[1,2],[2,3],[3,4],[1,3]] |
1 | class Solution { |
763. Partition Labels
Medium
You are given a string s
. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s
.
Return a list of integers representing the size of these parts.
Example 1:
1 | Input: s = "ababcbacadefegdehijhklij" |
1 | class Solution { |
- 统计每一个字符最后出现的位置
- 从头遍历字符,并更新字符的最远出现下标,如果找到字符最远出现位置下标和当前下标相等了,则找到了分割点
如图:
56. Merge Intervals
Medium
Given an array of intervals
where intervals[i] = [starti, endi]
, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
1 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] |
1 | class Solution { |
53. Maximum Subarray
Medium
Example 1:
1 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] |
Example 2:
1 | Input: nums = [1] |
1 | class Solution { |
55. Jump Game
You are given an integer array nums
. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, or false
otherwise.
Example 1:
1 | Input: nums = [2,3,1,1,4] |
1 | class Solution { |
45. Jump Game II
Medium
You are given a 0-indexed array of integers nums
of length n
. You are initially positioned at nums[0]
.
Each element nums[i]
represents the maximum length of a forward jump from index i
. In other words, if you are at nums[i]
, you can jump to any nums[i + j]
where:
0 <= j <= nums[i]
andi + j < n
Return the minimum number of jumps to reach nums[n - 1]
. The test cases are generated such that you can reach nums[n - 1]
.
Example 1:
1 | Input: nums = [2,3,1,1,4] |
1 | //////////////55 jump game/////////////// |
[toc]