Leetcode121 股票最大收益问题

题目描述:

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

示例

——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.

Solution1

很简单的问题,不必要思考的那么麻烦,两个指针,从后往前遍历就能解决。
遇到的问题:
之前很蠢的多此一举,把两个指针的差放到数组中,求数组的最大值。虽然是没有必要,但是出现了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]);
        }
    }
}

Solution2

运用动态规划的方法,把大于0的‘总’增量保存下来。

class Solution {
        public int maxProfit(int[] prices) {
        int maxCur = 0, maxSoFar = 0;
        for(int i = 1; i < prices.length; i++) {
            maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);
            maxSoFar = Math.max(maxCur, maxSoFar);
        }
        return maxSoFar;
    }
}

Runtime:
1ms

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值