Moderate 最大连续序列之和 @CareerCup
来源:互联网 发布:景观大数据破解 编辑:程序博客网 时间:2024/06/08 19:50
最大连续序列之和问题,思路就是保持两个变量,一个记录到当前位置最大的和(maxSum),还有一个记录当前位置的和(curSum)
当curSum+a[i]<0时,curSum重置为0,表示不选择a[i]
如果>=0时,curSum += a[i]
package Moderate;/** * * You are given an array of integers (both positive and negative). Find the continuous sequence with the largest sum. Return the sum.EXAMPLEInput: {2, -8, 3, -2, 4, -10}Output: 5 (i.e., {3, -2, 4} )译文:给出一个整数数组(包含正数和负数),找到和最大的连续子序列,返回和。例子:输入: {2, -8, 3, -2, 4, -10}输出: 5 (即, {3, -2, 4} ) * */public class S17_8 {public static int getMaxSum(int[] a) {if(a.length == 0){return 0;}int maxSum = 0;int curSum = 0;for(int i=0; i<a.length; i++){if(curSum+a[i] >= 0){curSum += a[i];maxSum = Math.max(maxSum, curSum);}else{curSum = 0;}}return maxSum;}public static void main(String[] args) {int[] a = {2, -8, 3, -2, 4, -10};// int[] a = {-10, -8}; System.out.println(getMaxSum(a));}}
- Moderate 最大连续序列之和 @CareerCup
- 最大连续子序列之和
- 最大连续子序列之和
- 最大连续子序列之和
- 最大连续子序列之和
- 最大连续子序列之和
- 最大子连续序列之和
- 最大连续子序列之和
- 最大连续子序列之和,最大连续子序列乘积
- 计算最大连续子序列之和
- 输出最大连续子序列之和
- 最大连续子序列之和的问题
- Moderate 猜测序列hit或是pseudo-hit @CareerCup
- Moderate 查单词 @CareerCup
- 最大连续子序列之和(动态规划)
- 求最大连续子序列之和 立方算法
- 寻找连续的元素相加之和为最大的序列
- 算法进化历程之“最大连续子序列之和”
- javascript进阶(一)
- QtTelnet
- javascript进阶(二)
- Apache 不能解析 jsp
- android --Bundle
- Moderate 最大连续序列之和 @CareerCup
- window8 下PEiD不能正常工作
- Moderate 查单词 @CareerCup
- Android 开发过程笔记
- Struts2运行机制
- Django admin定制
- 莱特币_质数币_比奥币_点点币_阿侬币、瑞波币等介绍,带你认识比特币和各种虚拟货币
- JS取文本框中最小值
- php字符串转数组