package 面试题_16_17_连续数列;
public class Solution {
public int maxSubArray(int[] nums) {
if (nums.length == 1) {
return nums[0];
}
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
nums[i] = Math.max(nums[i - 1] + nums[i], nums[i]);
max = Math.max(max, nums[i]);
}
return max;
}
public static void main(String [] args) {
Solution x = new Solution();
System.out.println(x.maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
}
}
```
class Solution:
def maxSubArray(self, nums) -> int:
if len(nums) == 1:
return nums[0]
max_sub = nums[0]
for i in range(1, len(nums)):
nums[i] = max(nums[i - 1] + nums[i], nums[i])
max_sub = max(max_sub, nums[i])
return max_sub
if __name__ == '__main__':
x = Solution()
print(x.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))