Similar to get the max subarray-(2ms/java)-also the idea to solve the buy and sell stock 2


  • 0
    D

    public class Solution {
    public int maxProfit(int[] prices) {
    if(prices.length==0||prices.length==1)
    {
    return 0;
    } //consider the special condition
    int[] A=new int[prices.length-1];
    for(int i=0;i<prices.length-1;i++)
    {
    A[i]=prices[i+1]-prices[i];
    } //get the new array of the difference between two numbers
    int max = 0, sum = 0;
    for (int i = 0; i < A.length; i++) {
    if (sum < 0)
    sum = A[i];
    else
    sum += A[i];
    if (sum > max)
    max = sum;
    }
    return max;//change the problem to get the most subarray in new array
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.