剑指offer:子数组的最大和
来源:互联网 发布:vb.net 创建文件夹 编辑:程序博客网 时间:2024/05/22 08:25
题目:输入一个整形数组,数组里有整数也有负数,数组中一个或者多个整数组成一个子数组,求所有子数组和的最大值。
package com.interview;public class FindGreatestSubArray {private boolean valid = true; //这是为了标记输入是否有效的变量private int greatestSubArray(int[] A) {if (A.length < 1) {valid = false;return 0;}int result = A[0], sum = 0;for (int i = 0; i < A.length; ++i) {if (A[i] < 0) {if (result < 0) { //这是为了防止全是负数的情况if (result < A[i])result = A[i];} elsesum = 0;} else {if (A[i] >= 0)sum += A[i];if (result < sum)result = sum;}}return result;}public static void main(String[] args) {// TODO Auto-generated method stubFindGreatestSubArray fbsa = new FindGreatestSubArray();// int[] A = new int[] { -2, -2, 3, 10, 1, -4, 7, 2, 4, -5 };//int[] A = new int[] { -5, -3, -1, -2, -8 };//int[] A=new int[]{1};int[] A=new int[]{-2, -2, 3, 1, -4, 7, -5};int result = fbsa.greatestSubArray(A);if (result == 0) {if (!fbsa.valid)System.out.println("invalid input!");}System.out.println(result);}}
0 0
- 剑指offer:子数组的最大和
- [剑指offer]连续子数组最大和
- 剑指offer-最大连续子数组和
- 剑指offer:连续子数组最大和
- 剑指offer---连续子数组最大和
- 【剑指offer】连续子数组最大和
- 剑指offer:31-连续子数组的最大和
- 剑指Offer之连续子数组的最大和
- 【剑指offer】连续子数组的最大和
- 剑指offer-31:连续子数组的最大和
- 剑指offer--连续子数组的最大和
- 剑指Offer之 - 连续子数组的最大和
- 剑指offer之连续子数组的最大和
- 剑指offer 31 - 连续子数组的最大和
- 《剑指offer》连续子数组的最大和
- 剑指offer:连续子数组的最大和
- 【剑指Offer】连续子数组的最大和
- 剑指offer-连续子数组的最大和
- 随记数new id()
- 我没有一个好朋友了
- UVA 301 POJ 1040- Transportation DFS 回溯
- ldap根据dn值查找objectClass
- 页面中用s标签接html代码
- 剑指offer:子数组的最大和
- C语言中全局变量、局部变量、静态全局变量、静态局部变量的区别
- qt creator 在linux下不显示控制台 及xterm字体配置
- 疯狂Java讲义——第1章 环境搭建
- Python中的getattr()函数详解
- PHP的几种运行模式
- js 添加、移除、检测 className
- MFC 常用功能汇总
- 几种C++ std::string和std::wstring相互转换的转换方法(转)