feat: 2025-10-31打卡
This commit is contained in:
22
121.best-time-to-buy-and-sell-stock.java
Normal file
22
121.best-time-to-buy-and-sell-stock.java
Normal file
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* @lc app=leetcode id=121 lang=java
|
||||
*
|
||||
* [121] Best Time to Buy and Sell Stock
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
class Solution {
|
||||
public int maxProfit(int[] prices) {
|
||||
if(prices == null || prices.length == 0) {
|
||||
return 0;
|
||||
}
|
||||
int min = prices[0], profit = 0;
|
||||
for(int i=1; i<prices.length; i++) {
|
||||
profit = Math.max(profit, prices[i] - min);
|
||||
min = Math.min(min, prices[i]);
|
||||
}
|
||||
return profit;
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
37
123.best-time-to-buy-and-sell-stock-iii.java
Normal file
37
123.best-time-to-buy-and-sell-stock-iii.java
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* @lc app=leetcode id=123 lang=java
|
||||
*
|
||||
* [123] Best Time to Buy and Sell Stock III
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
class Solution {
|
||||
public int maxProfit(int[] prices) {
|
||||
int[] ldp = new int[prices.length];
|
||||
int[] rdp = new int[prices.length];
|
||||
for(int i=0; i<ldp.length; i++) {
|
||||
ldp[i] = 0;
|
||||
rdp[i] = 0;
|
||||
}
|
||||
int lmin = prices[0], maxProfit=0;
|
||||
for(int i=1; i<ldp.length; i++) {
|
||||
maxProfit = Math.max(maxProfit, prices[i]-lmin);
|
||||
lmin = Math.min(lmin, prices[i]);
|
||||
ldp[i] = maxProfit;
|
||||
}
|
||||
int rmax = prices[prices.length-1];
|
||||
maxProfit = 0;
|
||||
for(int i=rdp.length-2; i>=0; i--) {
|
||||
maxProfit = Math.max(maxProfit, rmax - prices[i]);
|
||||
rmax = Math.max(rmax, prices[i]);
|
||||
rdp[i] = maxProfit;
|
||||
}
|
||||
int profit = ldp[ldp.length-1];
|
||||
for(int i=0; i<ldp.length-1; i++) {
|
||||
profit = Math.max(profit, ldp[i] + rdp[i+1]);
|
||||
}
|
||||
return profit;
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
32
152.maximum-product-subarray.java
Normal file
32
152.maximum-product-subarray.java
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* @lc app=leetcode id=152 lang=java
|
||||
*
|
||||
* [152] Maximum Product Subarray
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
class Solution {
|
||||
public int maxProduct(int[] nums) {
|
||||
int min = 1, max = 1, r = nums[0], curMax, curMin;
|
||||
for(int i = 0; i< nums.length; i++) {
|
||||
if(nums[i] == 0) {
|
||||
max = min = 0;
|
||||
r = Math.max(r, 0);
|
||||
} else if(nums[i] > 0) {
|
||||
curMax = Math.max(nums[i], max*nums[i]);
|
||||
curMin = Math.min(nums[i], min*nums[i]);
|
||||
max = curMax;
|
||||
min = curMin;
|
||||
} else {
|
||||
curMax = Math.max(min * nums[i], nums[i]);
|
||||
curMin = Math.min(max*nums[i], nums[i]);
|
||||
max = curMax;
|
||||
min = curMin;
|
||||
}
|
||||
r = Math.max(max, r);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
Reference in New Issue
Block a user