您的代码第 8 行的 thisSum 在循环i的开始部分被重置,
但是循环 j 中的 thisSum 会继续在循环 j 中添加数组a [ ]元素。
通常我会替换值并假设值来理解循环是如何工作的。
假设向量 a 有 3 个 int 元素 10,-20,100
因此 a.size() = 3
//maxSum is initialized in the function
int maxSum = 0;
//Start First i loop
int i = 0; i < 3;
int thisSum = 0;
int j = i = 0; j < 3;
thisSum += a[0];
//thisSum = 10
//10 > 0
if (thisSum > maxSum) maxSum = thisSum = 10;
int j = i = 1; j < 3;
thisSum += a[1];
//thisSum = -10
// -10 not > 10
int j = i = 2; j < 3;
thisSum += a[2];
//thisSum = 90
//90 > 10
if (thisSum > maxSum) maxSum = thisSum = 90;
//End First i loop
//Start 2nd i loop
int i = 1; i < 3;
int thisSum = 0;
int j = i = 1; j < 3;
thisSum += a[1];
//thisSum = -20
//-20 not > 90
int j = i = 2; j < 3;
thisSum += a[2];
//thisSum = 80
//80 not > 90
//End 2nd i loop
//Start 3rd i loop
int i = 2; i < 3;
int thisSum = 0;
int j = i = 2; j < 3;
thisSum += a[2];
//thisSum = 100
//100 > 90
if (thisSum > maxSum) maxSum = thisSum = 100;
//End 3rd i loop
//return 100
//return maxSum
该函数的概念是它尝试从最小索引元素到最大索引参数逐步删除项目,以获得最大总和。
第一个循环 i:maxSum = 90
第二个循环 i:maxSum = 90(删除 10)
第三个循环 i : maxSum = 100 (删除 10,-20)