04、位元組跳動-動態與貪心
阿新 • • 發佈:2018-12-10
1、買賣股票的最佳時機
class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length < 1) { return 0; } int max = 0; int min = prices[0]; for(int i = 0; i <prices.length ; i++){ if (prices[i] < min) min = prices[i]; else{ if(max < prices[i] - min) max = prices[i] - min; } } return max; } }
參考:https://blog.csdn.net/weixin_41876155/article/details/80036893
2、買賣股票的最佳時機 II
public class OneHundredAndTwentyTwo { public static int maxProfit(int[] prices) { int sum = 0; for(int i = prices.length - 1;i>0;i--) { if(prices[i] <= prices[i-1]) { continue; } else { sum += prices[i] - prices[i-1]; } } return sum; } public static void main(String[] args) { int[] nums = new int[] {7,6,5,9,1,3}; System.out.println(maxProfit(nums)); } }
原文:https://blog.csdn.net/xushiyu1996818/article/details/81200240
3、最大正方形
public class Solution { public int maximalSquare(char[][] matrix) { if(matrix.length == 0) return 0; int m = matrix.length, n = matrix[0].length; int max = 0; int[][] dp = new int[m][n]; // 第一列賦值 for(int i = 0; i < m; i++){ dp[i][0] = matrix[i][0] - '0'; max = Math.max(max, dp[i][0]); } // 第一行賦值 for(int i = 0; i < n; i++){ dp[0][i] = matrix[0][i] - '0'; max = Math.max(max, dp[0][i]); } // 遞推 for(int i = 1; i < m; i++){ for(int j = 1; j < n; j++){ dp[i][j] = matrix[i][j] == '1' ? Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1])) + 1 : 0; max = Math.max(max, dp[i][j]); } } return max * max; } }
參考:https://segmentfault.com/a/1190000003709497
https://blog.csdn.net/qq_35170267/article/details/81202103
4、最大子序和
class Solution {
public int maxSubArray(int[] nums) {
int current=nums[0];
int sum=nums[0];
//我們考慮如果全是負數,那麼返回最大的負數,如果最後的和為正,那麼就使用掃描法
for(int i=1;i<nums.length;i++) {
if(current<0)
current=nums[i];//當前數小於0 肯定會捨去(否則將會影響接下來的和),換為下一個數
else
current+=nums[i];//如果當前數不小於0,那麼他會對接下來的和有積極影響
if(current>sum)
sum=current;//這裡既實現了負數返回最大也實現了掃描法
//這裡其實已經隱式的列舉了所有可能,保留了所有可能的最大值
}
return sum;
}
}
5、三角形最小路徑和
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
for (int i = triangle.size()-2; i >= 0; i--){
for (int j = 0; j < triangle.get(i).size(); j++){
triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)));
}
}
return triangle.get(0).get(0);
}
}
參考:https://blog.csdn.net/fmuma/article/details/80167433
6、俄羅斯套娃信封問題
class Solution {
public int maxEnvelopes(int[][] envelopes) {
if(envelopes.length==0){
return 0;
}
Arrays.sort( envelopes, new Comparator<int[]>() {
@Override
public int compare(int[] ints, int[] t1) {
return ints[0]-t1[0]!=0?ints[0]-t1[0]:ints[1]-t1[1];
}
});
int[] dp=new int[envelopes.length];
Arrays.fill(dp,1);
for(int i=0;i<envelopes.length;++i){
int[] ed=envelopes[i];
for(int j=0;j<i;++j){
int[] st=envelopes[j];
if(ed[0]>st[0]&&ed[1]>st[1]&&dp[j]+1>dp[i]){
dp[i]=dp[j]+1;
}
}
}
int ans=0;
for(int i=0;i<envelopes.length;++i){
ans=Math.max(ans,dp[i]);
}
return ans;
}
}
原文:https://blog.csdn.net/Viscu/article/details/82354257