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

Posted dbbf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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     }

 








以上是关于Array——LeetCode——Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]题解(python):123-Best Time to Buy and Sell Stock III

[LeetCode]题解(python):122-Best Time to Buy and Sell Stock II

Leetcode 121. Best Time to Buy and Sell Stock JAVA语言

Leetcode 123. Best Time to Buy and Sell Stock III JAVA语言

Leetcode 122. Best Time to Buy and Sell Stock II JAVA语言

Go 实现 LeetCode 全集