Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9ae14c3

Browse files
committed
add 53, 121
1 parent559615e commit9ae14c3

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* key: just use two variables, 'minPrice' to track the loweset prices,
3+
* 'maxProfit' to track max profit, scan the array once.
4+
*
5+
*@param {number[]} prices
6+
*@return {number}
7+
*/
8+
varmaxProfit=function(prices){
9+
if(prices.length===0)return0;
10+
11+
varminPrice=prices[0];
12+
varmaxProfit=0;
13+
14+
for(vari=1;i<prices.length;i++){
15+
maxProfit=Math.max(maxProfit,prices[i]-minPrice);
16+
minPrice=Math.min(minPrice,prices[i]);
17+
}
18+
19+
returnmaxProfit;
20+
};

‎Medium/53-maximumSubarray.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
*@param {number[]} nums
3+
*@return {number}
4+
*/
5+
varmaxSubArray=function(nums){
6+
varmax=nums[0];
7+
varsums=[max];
8+
for(vari=1;i<nums.length;i++){
9+
// here is the key, the dynamic programming format,
10+
// sums means maximunEndingHere (at i), it is always the maxium value of
11+
// current element value and the previous max plus the current element itself.
12+
sums[i]=Math.max((sums[i-1]+nums[i]),nums[i]);
13+
max=Math.max(max,sums[i]);
14+
}
15+
16+
returnmax;
17+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp