贪心算法
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 8 namespace test 9 { 10 class Program 11 { 12 const int COUNT = 10; 13 14 const int MIDDLE = 0; 15 static void Main(string[] args) 16 { 17 // 将数组赋值(-100 -- 100) 18 int[] iArray = new int[COUNT]; 19 Random random = new Random(DateTime.Now.Millisecond); 20 for (var i = 0; i < COUNT;i++ ) 21 { 22 iArray[i] = random.Next(-COUNT, COUNT); 23 } 24 25 // 下面是算法 26 List<Caculation> cache = new List<Caculation>(); 27 var data = new Caculation(); 28 int add = 0; 29 30 for (int i = 0; i < COUNT ; i++) 31 { 32 add += iArray[i]; 33 34 if (add > 0) 35 { 36 if (add >= data.max) 37 { 38 data.end = i; 39 data.max = add; 40 if (i == COUNT - 1) 41 { 42 cache.Add(data); 43 } 44 } 45 else 46 { 47 cache.Add(data); // 提交上一个 48 var temp = new Caculation(data); 49 temp.end = i; // 下一个不归零 50 temp.max = add; 51 data = temp; 52 } 53 } 54 else 55 { 56 data.max = add; 57 data.end = i; 58 cache.Add(data); // 提交这一个 59 add = 0; // 下一个归零 60 var temp = new Caculation(); 61 temp.start = i + 1; 62 data = new Caculation(temp); 63 } 64 } 65 66 67 int max = 0; 68 Caculation c = null; 69 for (var i = 0; i < cache.Count; i++) 70 { 71 Console.WriteLine(cache[i].ToString()); 72 if (cache[i].max > max) 73 { 74 c = cache[i]; 75 max = c.max; 76 } 77 } 78 79 80 81 //显示结果 82 int s = 0; 83 foreach (var i in iArray) 84 { 85 Console.Write(i+" , "); 86 s += i; 87 } 88 Console.WriteLine("\nThe Max is" + c); 89 90 Console.ReadLine(); 91 } 92 class Caculation 93 { 94 public int max; 95 public int start, end; 96 public Caculation() 97 { 98 this.max = 0; 99 this.start = 0; 100 this.end = 0; 101 } 102 public Caculation(Caculation c) 103 { 104 this.max = c.max; 105 this.start = c.start; 106 this.end = c.end; 107 } 108 public override string ToString() 109 { 110 return "This Caculation is Max: " + max + " Start: " + start + " end: " + end; 111 } 112 } 113 } 114 }