给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
This commit is contained in:
parent
940cd3b85a
commit
a854f1c12d
33
src/main/java/com/leetcode/huawei/MaxSubArray.java
Normal file
33
src/main/java/com/leetcode/huawei/MaxSubArray.java
Normal file
@ -0,0 +1,33 @@
|
||||
package com.leetcode.huawei;
|
||||
|
||||
/**
|
||||
* 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
|
||||
*
|
||||
* https://leetcode-cn.com/problems/maximum-subarray/
|
||||
*/
|
||||
public class MaxSubArray {
|
||||
|
||||
|
||||
public int maxSubArray(int[] nums) {
|
||||
int res = nums[0];
|
||||
int sum = 0;
|
||||
for (int num : nums) {
|
||||
if (sum > 0)
|
||||
sum += num;
|
||||
else
|
||||
sum = num;
|
||||
res = Math.max(res, sum);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
MaxSubArray maArray = new MaxSubArray();
|
||||
int[] arr = {-2,1,-3,4,-1,2,1,-5,4};
|
||||
int result = maArray.maxSubArray(arr);
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
}
|
34
src/main/java/com/leetcode/huawei/MinCostClimbingStairs.java
Normal file
34
src/main/java/com/leetcode/huawei/MinCostClimbingStairs.java
Normal file
@ -0,0 +1,34 @@
|
||||
package com.leetcode.huawei;
|
||||
/**
|
||||
*
|
||||
数组的每个下标作为一个阶梯,第 i 个阶梯对应着一个非负数的体力花费值 cost[i](下标从 0 开始)。
|
||||
每当你爬上一个阶梯你都要花费对应的体力值,一旦支付了相应的体力值,你就可以选择向上爬一个阶梯或者爬两个阶梯。
|
||||
请你找出达到楼层顶部的最低花费。在开始时,你可以选择从下标为 0 或 1 的元素作为初始阶梯。
|
||||
示例 1:
|
||||
|
||||
输入:cost = [10, 15, 20]
|
||||
输出:15
|
||||
解释:最低花费是从 cost[1] 开始,然后走两步即可到阶梯顶,一共花费 15 。
|
||||
示例 2:
|
||||
|
||||
输入:cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
|
||||
输出:6
|
||||
解释:最低花费方式是从 cost[0] 开始,逐个经过那些 1 ,跳过 cost[3] ,一共花费 6 。
|
||||
|
||||
来源:力扣(LeetCode)
|
||||
链接:https://leetcode-cn.com/problems/min-cost-climbing-stairs
|
||||
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
||||
*
|
||||
*/
|
||||
public class MinCostClimbingStairs {
|
||||
|
||||
public int minCostClimbingStairs(int[] cost) {
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user