Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. public int highestProductOf3(int[] arrayOfInts)
  2. {
  3. if (arrayOfInts.Length < 3)
  4. {
  5. throw new ArgumentException("Less than 3 items!");
  6. }
  7.  
  8. // Firstly we will separate specific array elements
  9. // into their own variables for better clarity and maintainability.
  10. // Working directly with specific array elements is generally
  11. // considered a bad practice which leads to errors because
  12. // it's hard to manage and refactor.
  13. int first = arrayOfInts[0];
  14. int second = arrayOfInts[1];
  15. int third = arrayOfInts[2];
  16.  
  17. // We're going to start at the 3rd item (at index 2)
  18. // so pre-populate highests and lowests based on the first 2 items.
  19. // We could also start these as null and check below if they're set
  20. // but this is arguably cleaner.
  21. int highest = Math.Max(first, second);
  22. int lowest = Math.Min(first, second);
  23.  
  24. int highestProductOf2 = first * second;
  25. int lowestProductOf2 = first * second;
  26.  
  27. // Except this one--we pre-populate it for the first /3/ items.
  28. // This means in our first pass it'll check against itself, which is fine.
  29. int highestProductOf3 = first * second * third;
  30.  
  31. // Walk through items, starting at index 2.
  32. for (var i = 2; i < arrayOfInts.Length; i++)
  33. {
  34. int current = arrayOfInts[i];
  35.  
  36. // Do we have a new highest product of 3?
  37. // It's either the current highest,
  38. // or the current times the highest product of two
  39. // or the current times the lowest product of two.
  40. highestProductOf3 = new int[] {
  41. highestProductOf3,
  42. current * highestProductOf2,
  43. current * lowestProductOf2
  44. }.Max();
  45.  
  46. // Do we have a new highest product of two?
  47. highestProductOf2 = new int[] {
  48. highestProductOf2,
  49. current * highest,
  50. current * lowest
  51. }.Max();
  52.  
  53. // Do we have a new lowest product of two?
  54. lowestProductOf2 = new int[] {
  55. lowestProductOf2,
  56. current * highest,
  57. current * lowest
  58. }.Max();
  59.  
  60. // Do we have a new highest?
  61. highest = Math.Max(highest, current);
  62.  
  63. // Do we have a new lowest?
  64. lowest = Math.Min(lowest, current);
  65. }
  66.  
  67. return highestProductOf3;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement