@@ -46,13 +46,10 @@ Note that buying on day 2 and selling on day 1 is not allowed because you must b
46
46
``` python
47
47
class Solution :
48
48
def maxProfit (self , prices : List[int ]) -> int :
49
- if not prices:
50
- return 0
51
- res = 0
52
- min_price = prices[0 ]
53
- for price in prices:
54
- min_price = min (min_price, price)
55
- res = max (res, price - min_price)
49
+ res, mi = 0 , prices[0 ]
50
+ for price in prices[1 :]:
51
+ res = max (res, price - mi)
52
+ mi = min (mi, price)
56
53
return res
57
54
```
58
55
@@ -61,40 +58,93 @@ class Solution:
61
58
``` java
62
59
class Solution {
63
60
public int maxProfit (int [] prices ) {
64
- if (prices == null ) return 0 ;
65
- int res = 0 ;
66
- int min = Integer . MAX_VALUE ;
67
- for (int price : prices) {
68
- min = Math . min(min, price);
69
- res = Math . max(res, price - min);
61
+ int res = 0 , mi = prices[0 ];
62
+ for (int i = 1 ; i < prices. length; ++ i) {
63
+ res = Math . max(res, prices[i] - mi);
64
+ mi = Math . min(mi, prices[i]);
70
65
}
71
66
return res;
72
67
}
73
68
}
74
69
```
75
70
71
+ ### ** C++**
72
+
73
+ ``` cpp
74
+ class Solution {
75
+ public:
76
+ int maxProfit(vector<int >& prices) {
77
+ int res = 0, mi = prices[ 0] ;
78
+ for (int i = 1; i < prices.size(); ++i) {
79
+ res = max(res, prices[ i] - mi);
80
+ mi = min(mi, prices[ i] );
81
+ }
82
+ return res;
83
+ }
84
+ };
85
+ ```
86
+
87
+ ### **Go**
88
+
89
+ ```go
90
+ func maxProfit(prices []int) int {
91
+ res, mi := 0, prices[0]
92
+ for i := 1; i < len(prices); i++ {
93
+ res = max(res, prices[i]-mi)
94
+ mi = min(min, prices[i])
95
+ }
96
+ return res
97
+ }
98
+
99
+ func max(a, b int) int {
100
+ if a > b {
101
+ return a
102
+ }
103
+ return b
104
+ }
105
+
106
+ func min(a, b int) int {
107
+ if a < b {
108
+ return a
109
+ }
110
+ return b
111
+ }
112
+ ```
113
+
76
114
### ** JavaScript**
77
115
78
116
``` js
79
117
/**
80
118
* @param {number[]} prices
81
119
* @return {number}
82
120
*/
83
- const maxProfit = function (prices ) {
84
- let min = prices[0 ];
85
- let profit = 0 ;
86
- for (let i = 0 ; i < prices .length ; i++ ) {
87
- if (prices[i] < min) {
88
- min = prices[i];
89
- }
90
- if (profit < prices[i] - min) {
91
- profit = prices[i] - min;
121
+ var maxProfit = function (prices ) {
122
+ let res = 0 ;
123
+ let mi = prices[0 ];
124
+ for (let i = 1 ; i < prices .length ; ++ i) {
125
+ res = Math .max (res, prices[i] - mi);
126
+ mi = Math .min (mi, prices[i]);
92
127
}
93
- }
94
- return profit;
128
+ return res;
95
129
};
96
130
```
97
131
132
+ ### ** C#**
133
+
134
+ ``` cs
135
+ public class Solution {
136
+ public int MaxProfit (int [] prices ) {
137
+ int res = 0 , mi = prices [0 ];
138
+ for (int i = 1 ; i < prices .Length ; ++ i )
139
+ {
140
+ res = Math .Max (res , prices [i ] - mi );
141
+ mi = Math .Min (mi , prices [i ]);
142
+ }
143
+ return res ;
144
+ }
145
+ }
146
+ ```
147
+
98
148
### ** ...**
99
149
100
150
```
0 commit comments