Easy
53. 最大子数组和
https://leetcode-cn.com/problems/maximum-subarray/
(1)题解1 效率较低
class Solution {
public int maxSubArray(int[] nums) {
//1.定义dp[i] 为前i个元素中 连续子数组的最大和
int[] dp = new int[nums.length + 1];
//2.初始化
dp[1] = nums[0];
int res = dp[1];
//3.状态转移
for(int i = 2;i<=nums.length;i++){
if(dp[i-1] <= 0){
dp[i] = nums[i - 1];
}else{
dp[i] = dp[i-1] + nums[i-1];
}
if(dp[i] > res) res = dp[i];
}
return res;
}
}
(2)题解2
class Solution {
public int maxSubArray(int[] nums) {
int sum = 0; //以当前元素做结尾的连续子序列的最大和
int res = nums[0];
for(int num : nums){
if(sum <= 0){
sum = num;
}else{
sum = sum + num;
}
res = Math.max(res,sum);
}
return res;
}
}
119. 杨辉三角 II
https://leetcode-cn.com/problems/pascals-triangle-ii/
class Solution {
public List<Integer> getRow(int rowIndex) {
int[][] dp = new int[rowIndex + 1][];
for (int i = 0; i < dp.length; i++) {
dp[i] = new int[i + 1];
for (int j = 0; j < dp[i].length; j++) {
if(j == 0 || j == dp[i].length - 1){
dp[i][j] = 1;
}else{
dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
}
}
}
List<Integer> res = new ArrayList<>();
for (int i : dp[rowIndex]) {
res.add(i);
}
return res;
}
}