Leetcode~121

题目描述:
给定一个序列,是股票一段时间内的价格,让你求出最大收益。

——Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
——Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

思考:
很简单的问题,不必要思考的那么麻烦,两个指针,从后往前遍历就能解决。
遇到的问题:
之前很蠢的多此一举,把两个指针的差放到数组中,求数组的最大值。虽然是没有必要,但是出现了java.lang.ArrayIndexOutOfBoundsException的问题,就是数组越界的问题。java.lang.ArrayIndexOutOfBoundsException(数组越界)处理方法

class Solution {
    public int maxProfit(int[] prices) {
        int maxprofit=0;
	//int n=prices.length;
	//int size=n*(n-1)/2;
	//int []array= new int [2*size];
        
    int j=0;
    int dec; 
	
	
	for(int i=prices.length-1;i>=0;i--){
		for(int k=i;k>=0;k--){
			 dec=prices[i]-prices[k];
			if(dec>=maxprofit)
                maxprofit=dec;
		}
		
	}
	
	
	return maxprofit;
        
        
        
    }
}

当你使用不合法的索引访问数组时会报数组越界这种错误,数组arr的合法错误范围是[0, arr.length-1];当你访问这之外的索引时会报这个错。这种错误很像字符串索引越界。但是,提示栏第1行可能就告诉我们错误的原因是数组越界了。
当处理数组越界时,可以尝试打印出遍历数组的索引,这样容易定位问题所在。

public class Test {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

coding的时候请用上你的脑子:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42662955/article/details/89384601
121
今日推荐