题解 | #买卖股票的最好时机(一)#

买卖股票的最好时机(一)

http://www.nowcoder.com/practice/64b4262d4e6d4f6181cd45446a5821ec

题目大意:求两个数差值最大

思路:构造一个两数之差的数组,求该数组中子串和最大

[7,1,5,3,6,4]

[-6,4,-2,3,-2]

ans = 5 //4-2+3

import java.util.*;
public class Solution {
    public int maxProfit (int[] prices) {
        // write code here
        int[] num = new int[prices.length - 1];
        int i,ans,temp;
        
        for(i = 0; i < num.length; i++)num[i] = prices[i+1] - prices[i];
        ans = temp = 0;
        
        for(i = 0; i < num.length; i++){
            temp+=num[i];
            ans = Math.max(temp,ans);
            if(temp <= 0)temp=0;
        }
        return ans;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务