fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. // index 0 1 2 3 4
  7. int b[5] = {5,-3,-5,15,5};
  8. int T=0;
  9. int n=5;
  10. int prv=0;
  11.  
  12. for(int i=0; i<n; i++)
  13. {
  14. // {Best answer till previous , current No , so if both are negative consider the ans is zero }
  15. // i=0
  16. // current = max(0+5 , 5 ,0)
  17. // prv = 5
  18. // T = max(0,5) = 5
  19.  
  20. //i=1
  21. // current = max(5+(-3) , -3 , 0)
  22. //prv = 2
  23. //T = max(5,2) = 5
  24.  
  25. //i=2
  26. //current = max(2+(-5) , -5 , 0) = max( -3 , -5 , 0) = 0 // becoz both -3 and -5 so the ans is consider as zero
  27. //prv = 0
  28. //T = max(5,0) = 5
  29.  
  30. //i=3
  31. //current = max(0+15 , 15 , 0 ) = max(15 , 15 , 0) = 15
  32. //prv = 15
  33. //T = max( 5, 15) = 15
  34.  
  35. //i=4
  36. //current = max(15+5 , 5 , 0 ) = (20 , 5 , 0) = 20
  37. //prv = 20
  38. //T = max(15,20) = 20
  39. int current = max({ prv+b[i] , b[i] , 0 });
  40. prv=current;
  41. T=max(T,current);
  42. }
  43. cout<<"Max sum of subarray of the whole array: "<<T; // 20 will be the final answer
  44. }
Success #stdin #stdout 0s 5332KB
stdin
Standard input is empty
stdout
Max sum of subarray of the whole array: 20