我的个人微信公众号:Microstrong
微信公众号ID:MicrostrongAI
微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!
知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities
题目链接:
题目描述:
题目:输入一个整型数组,数组里面有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。
牛客网上的题目描述:
解题思路:
(1)举例分析数组的规律
已经AC的Java代码:
public class greatestSumOfSubArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {-2, -8, -1, -5, -9};
int[] arr1 = {1, -2, 3, 10, -4, 7, 2, -5};
System.out.println(FindGreatestSumOfSubArray(arr1));
}
public static int FindGreatestSumOfSubArray(int[] array) {
if(array == null && array.length <= 0) {
return 0;
}
int Maxsum = Integer.MIN_VALUE;
int currentSum = 0;
for(int i=0; i<array.length; i++) {
currentSum += array[i];
if(currentSum < array[i]) {
currentSum = array[i];
}
if(currentSum > Maxsum) {
Maxsum = currentSum;
}
}
return Maxsum;
}
}
已经AC的Python代码:
# -*- coding:utf-8 -*-
class Solution:
def FindGreatestSumOfSubArray(self, array):
# write code here
if len(array) <= 0 and not array:
return None
maxSun = float('-inf')
currentSum = 0
for i in array:
currentSum += i
if currentSum < i:
currentSum = i
if currentSum > maxSun:
maxSun = currentSum
return maxSun
(2)动态规划法
设f(i)表示以第i个数字结尾的子数组的最大和,那么我们可以写出状态转移方程:
已经AC的Java代码:
public class greatestSumOfSubArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {-2, -8, -1, -5, -9};
int[] arr1 = {1, -2, 3, 10, -4, 7, 2, -5};
System.out.println(FindGreatestSumOfSubArray(arr1));
}
public static int FindGreatestSumOfSubArray(int[] array) {
int maxSum = Integer.MIN_VALUE;
int currentSum = 0;
for(int i=0; i<array.length; i++) {
if(currentSum <= 0) {
currentSum = array[i];
}else {
currentSum += array[i];
}
if(currentSum > maxSum) {
maxSum = currentSum;
}
}
return maxSum;
}
}
已经AC的Python代码:
class Solution:
def FindGreatestSumOfSubArray(self, array):
if not array:
return None
if len(array) > 0:
res = [0 for _ in range(len(array))]
res[0] = array[0]
for i in range(1, len(array)):
if res[i - 1] < 0:
res[i] = array[i]
else:
res[i] = res[i - 1] + array[i]
return max(res)