0
点赞
收藏
分享

微信扫一扫

【LeeCode】剑指 Offer 42. 连续子数组的最大和

北溟有渔夫 2022-12-09 阅读 102


【题目描述】

输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。

要求时间复杂度为O(n)

​​https://leetcode.cn/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/​​


【示例】

【LeeCode】剑指 Offer 42. 连续子数组的最大和_i++


【代码1】

admin

package com.company;
class Solution {

public int maxSubArray(int[] nums) {
int start;
int max = 0;
for (int i = 0; i < nums.length; i++){
for (int j = i + 1; j < nums.length; j++){
int tmp = 0;
start = i;
while (start <= j){
tmp += nums[start];
start++;
}
max = Math.max(tmp, max);
}

}
System.out.println(max);
return max;
}
}

public class Test {
public static void main(String[] args) {
int[] arr = {-2,1,-3,4,-1,2,1,-5,4};
new Solution().maxSubArray(arr);
}
}


【代码2】



举报

相关推荐

0 条评论