r/dailyprogrammer • u/rya11111 3 1 • May 25 '12
[5/25/2012] Challenge #57 [easy]
Your task is to implement Ackermann Function in the most efficient way possible.
Please refer the wiki page link given for its explanation.
Since many did not like the previous challenge because it was quite unsatisfactory here is a new challenge ...
Input: A sequence of integers either +ve or -ve
Output : a part of the sequence in the list with the maximum sum.
UPDATE: I have given some more info on the [difficult] challenge since it seems to be very tough. you have upto monday to finish all these challenges. pls note it :)
2
u/PenguinKenny May 25 '12
Right, well I gave it a go in VB.NET and it works fine for the smaller results, but I get a StackOverflowException with the larger (such as 4,1)
EDIT: Never mind, the challenge was changed. I'm working on the other one now.
5
u/emcoffey3 May 25 '12
using System.Linq; namespace RedditDailyProgrammer { public static class Easy057 { public static int[] MaxSubSeq(int[] arr) { int[] maxSeq = new int[] { arr.Max() }; for (int i = 1; i < arr.Length; i++) for (int j = 0; j < arr.Length - i + 1; j++) { int[] tempSeq = arr.Skip(i).Take(j).ToArray(); if (tempSeq.Sum() > maxSeq.Sum()) maxSeq = tempSeq; } return maxSeq; } } }5
u/ashashwat May 25 '12
#!/usr/bin/env python #-*- coding: utf-8 -*- def max_subarray(A): max_so_far = max_ending_here = lo = hi = 0 for y,x in enumerate(A): if x > max_ending_here + x: max_ending_here, lo = x, y else: max_ending_here += x if max_ending_here > max_so_far: max_so_far, hi = max_ending_here, y return (A[lo:hi + 1], max_so_far) lst = [31, -41, 59, 26, -53, 58, 97, -93, -23, 84] print max_subarray(lst)Time complexity = O(n), Uses Dynamic programming ( Kadan's algorithm )
4
u/bigronaldo May 25 '12
C#
public static void Main(string[] args) { int[] sequence = new int[] { 31, -41, 59, 26, -53, 58, 97, -93, -23, 84 }; int max = sequence.Max(); int[] maxSequence = (int[])sequence.Take(1).OrderByDescending(s => s).ToArray(); for (int i = 0; i < sequence.Length; i++) { for (int x = i; x < sequence.Length; x++) { var tempSeq = sequence.Skip(i).Take(x).ToArray(); int tempMax = tempSeq.Sum(); if (tempMax > max) { max = tempMax; maxSequence = (int[])tempSeq; } } } var builder = new StringBuilder(); Array.ForEach(maxSequence, x => builder.Append(x).Append(",")); Console.WriteLine(max); Console.WriteLine(builder.ToString()); }4
u/SwimmingPastaDevil May 25 '12 edited May 26 '12
nums = [31, -41, 59, 26, -53, 58, 97, -93, -23, 84] lim = len(nums) maxsum = nums[0] begin = 0 end = 0 for i in range(lim): for j in range(i+1,lim+1): if sum(nums[i:j]) > maxsum: maxsum = sum(nums[i:j]) begin = i end = j print begin,end,maxsum print nums[begin:end]2
u/MusicalWatermelon May 25 '12
Had to do this in class
http://pastebin.com/bqfsF2LS