Thursday, 17 December 2015

Largest sum contiguous subarray

Problem statement;

You need to find combination of stock brought and sell with maximum profile if brought and sold only once

Ex.if I purchase stock 4th day and sold at 7th day max profile will be 6 any other combination would  have lesser profit.

Out out is 4th day 7th day amount is 6.




import java.util.Scanner;
 
/**
 * @author Gaurang Sheth
 * Largest Sum Contiguous Subarray
 */
public class TestMain {
 //Test input - -2 1 -3 4 -1 2 1 -5 4
 public static void main(String[] args) {
  
  //System.out.println(compStr(null));
  System.out.println("Enter size of array :");
  //Scanner scan = new Scanner(System.in);
  int  n = Integer.parseInt(args[0]);
 
  int[] arr = new int[n];
  for (int i = 0; i < n; i++) {
   arr[i] = Integer.parseInt(args[i+1]);
 
  }

  System.out.println(n);
  System.out.println(arr.toString());
  int maxSum = 0;
  String s="";
  for (int j = 0; j < n; j++) {
   //int x = n;
   for (int x = n; x > j ; x--) {
    int sum = 0;
    for (int i = j; i < x  ; i++) {
     sum += arr[i];
    }
    System.out.println("Start"+j+ " End "+ x+"--SUM -- >"+sum);
    if(sum > maxSum){
     maxSum = sum;
     s = "Start"+j+ " End "+ x;
    }
   }
  
  }
  System.out.println(s +" - "+maxSum);
 
 }
 //-2 1 -3 4 -1 2 1 -5 4


}