youknow.za.net : fred.dhiren.za.net : dhiren.za.net : jahn.za.net : coleslawesome : 1.21 giggawatts : eternal





 

 Programming Riddle of the Day, 11 March 2008
youknow
Posted: Mar 11 2008, 09:32 AM


Final level boss


Group: Admins
Posts: 353
Member No.: 3
Joined: 30-January 07



In this challenge, given an array of integers, the goal is to efficiently find the start and end indices of the sub array that has the greatest value when all of its elements are summed together. Note that because some elements of the array may be negative, the problem is not solved by simply returning the start and end elements of the array.

Here are some samples of the the integer arrays {} and the expected output:

QUOTE

{1, 2, -5, 4, -3, 2}
From 3 to 3 equals 4

{1, 2, -5, 4, 1, -3, 2}
From 3 to 4 equals 5

{1, 2, 0, 1}
From 0 to 3 equals 4

{10, 10, -1, 10, 5}
From 0 to 4 equals 34

{100, -10, -100, -1, 50}
From 0 to 0 equals 100

{10, 10, -100, -1, 50}
From 4 to 4 equals 50

{-1, -1, -1, -1, -1}
From 0 to 0 equals -1

{10, 10, -21, 10, 10}
From 0 to 1 equals 20

{-5, -4, -1, -3, -2}
From 2 to 2 equals -1

{10, -1, 0, -2, -1, -1, -1, 20}
From 0 to 7 equals 24


--------------------
The complexity of software is an essential property, not an accidental one. Hence, descriptions of a software entity that abstract away its complexity often abstracts away its essence. -Frederick P. Brooks, No silver bullet, 1987
Top
bcn
Posted: Mar 12 2008, 06:41 AM


Member


Group: Members
Posts: 12
Member No.: 83
Joined: 28-January 08



static void find_highest(int[] a, out int start, out int end, out int hightotal)
{
int sum = 0;
int total = 0;
start = 0;
end = 0;
hightotal = 0;


for (int i = 0; i < a.Length; i++)
{
sum = a[i];

for (int j = i + 1; j < a.Length; j++)
if ((sum + a[j]) > sum)
{
sum += a[j];
end = j;
}
else
j = a.Length;

if (sum > total)
{
total = sum;
start = i;
}
}

hightotal = total;
}




int[] a = new int[] { 1, 2, 3, -4, -5 };

int start = 0;
int end = 0;
int hightotal = 0;

find_highest(a, out start, out end, out hightotal);


--------------------
user posted image
Top
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:
« Next Oldest | Techie of the day | Next Newest »


Topic Options



Hosted for free by InvisionFree (Terms of Use: Updated 7/7/05) | Powered by Invision Power Board v1.3 Final © 2003 IPS, Inc.
Archive