因此,我们只需要对数组 gain 进行一次遍历,在遍历到第 i 个元素时,使用前缀和的思想维护前 i 个元素的和,并用和更新答案即可。
代码
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intlargestAltitude(vector<int>& gain){ int ans = 0, sum = 0; for (int x: gain) { sum += x; ans = max(ans, sum); } return ans; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10
classSolution { publicintlargestAltitude(int[] gain) { intans=0, sum = 0; for (int x : gain) { sum += x; ans = Math.max(ans, sum); } return ans; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10
publicclassSolution { publicintLargestAltitude(int[] gain) { int ans = 0, sum = 0; foreach (int x in gain) { sum += x; ans = Math.Max(ans, sum); } return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7
classSolution: deflargestAltitude(self, gain: List[int]) -> int: ans = total = 0 for x in gain: total += x ans = max(ans, total) return ans
[sol1-C]
1 2 3 4 5 6 7 8 9 10
#define MAX(a, b) ((a) > (b) ? (a) : (b))
intlargestAltitude(int* gain, int gainSize){ int ans = 0, sum = 0; for (int i = 0; i < gainSize; i++) { sum += gain[i]; ans = MAX(ans, sum); } return ans; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8
var largestAltitude = function(gain) { let ans = 0, sum = 0; for (const x of gain) { sum += x; ans = Math.max(ans, sum); } return ans; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funclargestAltitude(gain []int) (ans int) { total := 0 for _, x := range gain { total += x ans = max(ans, total) } return }
funcmax(a, b int)int { if b > a { return b } return a }