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

Appearance settings

Latest commit

 

History

History
History
37 lines (34 loc) · 1.05 KB

File metadata and controls

37 lines (34 loc) · 1.05 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package LeetCode.array;
/**
* Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction
(ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
* @author Administrator
*
*/
public class LeetCode121 {
/**
public int maxProfit(int[] prices) {
int maxProfile = 0;
for(int i = 0; i < prices.length-1; i++) {
int buy = prices[i];
for(int j = i+1; j < prices.length; j++) {
int profile = prices[j] - buy;
if (maxProfile < profile) {
maxProfile = profile;
}
}
}
return maxProfile;
}
*/
public int maxProfit(int[] prices) {
int max = 0;
int cur = 0;
for(int i = 1; i < prices.length; i++) {
cur = Math.max(0, cur += prices[i] - prices[i-1]);
max = Math.max(cur, max);
}
return max;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.