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

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

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;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
06-25 09:33
厦门大学 Java
程序员饺子:现在日常估计没啥hc了,等到八月多估计就慢慢有了。双九✌🏻不用焦虑的
投递快手等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务