标签:console [] ext title max name ensure mes car
给定K个整数组成的序列{ N?1??, N?2??, ..., N?K?? },“连续子列”被定义为{ N?i??, N?i+1??, ..., N?j?? },其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。
本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:
输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。
在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。
6
-2 11 -4 13 -5 -2
20
c# 版 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int.Parse(Console.ReadLine());
var ls = Console.ReadLine().Split(‘ ‘);
int max = 0, nowmax = 0;
int x=0, y=0;
int nowX = 0, nowY = 0;
for(int i=0;i<ls.Length;i++)
{
nowX = 0;
var item = ls[i];
var temp = int.Parse(item);
if(nowmax==0)
{
nowX = i;
}
nowmax += temp;
if(nowmax>0)
{
nowY = i;
if (nowmax > max)
{
max = nowmax;
x = nowX;
y = nowY;
}
}
else
{
nowmax = 0;
}
}
Console.WriteLine(max);
}
}
}
标签:console [] ext title max name ensure mes car
原文地址:https://www.cnblogs.com/interim/p/9723173.html