Array——LeetCode——Best Time to Buy and Sell Stock

【学到的知识点——一般for循环,三个语句执行顺序】
1、语句1,语句2,主语句,语句3

【学到的知识点——数组[]和null,length分别有什么区别】
1、数组为null时,length不能访问
2、数组为[]时候,length为0
-----------------------------------------------------------------------------------------------------
【反思】

-----------------------------------------------------------------------------------------------------
【别人的Java解法代码】

-----------------------------------------------------------------------------------------------------
【自己的Java解法代码】

 1     public static int maxProfit(int[] prices) {
 2         //1、先取一个数字
 3         //2、后面每个比他大的,减来看tmp1。
 4         //3、后面每个比他小的,减来看tmp2。
 5         int max = 0;
 6         int tmpMax = 0;
 7         int tmp = 0;
 8         if (prices != null && prices.length != 0) {
 9             tmp = prices[0];
10         } else {
11             return 0;
12         }
13         for (int  i = 1; i < prices.length; i++) {
14             if (prices[i] > tmp) {                //1、tmpMax存放当前最大值(长就卖)
15                 tmpMax = prices[i] - tmp;
16             } else {
17                 tmp = prices[i];                    //2、tmp存放当前最小值(最小值)
18             }
19             max = tmpMax > max ? tmpMax : max;
20         }
21         return max;
22         
23     }

猜你喜欢

转载自www.cnblogs.com/Dbbf/p/9639415.html